Exemplo n.º 1
0
        protected SubProgram(IProgram program)
        {
            if (null == program)
                throw new ArgumentNullException(nameof(program));

            _program = program;
        }
        public Boolean GetLinkStatus(IProgram program)
        {
            int linkStatus;
            GL.GetProgram(program.ProgramId, GetProgramParameterName.LinkStatus, out linkStatus);

            return (Boolean)linkStatus;
        }
Exemplo n.º 3
0
 /// <summary>
 /// Creates an instance of an Interpreter. Each of the parameters except program is optional..
 /// </summary>
 /// <param name="program">The program to execute. If this is null, the empty program is executed.</param>
 /// <param name="tape">The tape to use as a memory story. If this is null, a default tape is used.</param>
 /// <param name="input">The input source to use. If this is null then Console.In is used.</param>
 /// <param name="output">The output source to use. If this is null then Console.Out is used.</param>
 public Interpreter(IProgram program, Tape tape = null, TextReader input = null, TextWriter output = null)
 {
     _program = program;
     _tape = tape ?? Tape.Default;
     _input = input ?? Console.In;
     _output = output ?? Console.Out;
 }
        public LoggingConfiguration(IProgram program, IOperatingSystem os, IVSServices vsservice)
        {
            NLog.Config.LoggingConfiguration conf;
            string assemblyFolder = program.ExecutingAssemblyDirectory;
            try
            {
                conf = new XmlLoggingConfiguration(Path.Combine(assemblyFolder, "NLog.config"), true);
            }
            catch (Exception ex)
            {
                vsservice.ActivityLogError(string.Format(CultureInfo.InvariantCulture, "Error loading nlog.config. {0}", ex));
                conf = new NLog.Config.LoggingConfiguration();
            }

            var fileTarget = conf.FindTargetByName("file") as FileTarget;
            if (fileTarget == null)
            {
                fileTarget = new FileTarget();
                conf.AddTarget(Path.GetRandomFileName(), fileTarget);
                conf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));
            }
            fileTarget.FileName = Path.Combine(os.Environment.GetLocalGitHubApplicationDataPath(), "extension.log");
            fileTarget.Layout = layout;

            try
            {
                LogManager.Configuration = conf;
            }
            catch (Exception ex)
            {
                vsservice.ActivityLogError(string.Format(CultureInfo.InvariantCulture, "Error configuring the log. {0}", ex));
            }
        }
Exemplo n.º 5
0
 public OutputWindow(IProgram program)
 {
     _program = program;
     Width = 512;
     Height = 512;
     Background = Brushes.Transparent;
     var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(50), DispatcherPriority.Render, OnTimer,
                                     Dispatcher);
     timer.Start();
 }
Exemplo n.º 6
0
 public AppStartController(AppConfiguration appConfiguration)
 {
     _application = DependencyResolver.GetImplementation<IProgram> ("IProgram", new object[] { appConfiguration });
     _appWidget = new AppStartWidget ();
     _appWidget.SetApp (appConfiguration.Name, appConfiguration.Command);
     _appWidget.Start += AppWidgetStart;
     _appWidget.Stop += AppWidgetStop;
     _application.HasExited += Application_HasExited;
     _application.HasStarted += Application_HasStarted;
     _appName = appConfiguration.Name;
 }
Exemplo n.º 7
0
 //ILogger Log = ServiceRegistration.Get<ILogger>();
 public bool DoSomethingWithProgram(IProgram program)
 {
     Log.Debug("SlimTv Button SlimTvRunSingleEPG was pressed");
     if (Main_GUI.Instance != null)
     {
         Main_GUI.Instance.Title(program.Title);
         Main_GUI.Instance.Name(program.Title);
         string mycommand = "RUN_EPG_SINGLE//VIEWONLY=TRUE//TITLE//NAME";
         Log.Debug("Executing command " + mycommand);
         Main_GUI.Instance.Command(mycommand);
     }
     return true;
 }
 //ILogger Log = ServiceRegistration.Get<ILogger>();
 public bool DoSomethingWithProgram(IProgram program)
 {
     Log.Debug("SlimTvTvWishListQuickMenu was pressed");
     if (Main_GUI.Instance != null)
     {
         Main_GUI.Instance.Title(program.Title);
         Main_GUI.Instance.Name(program.Title);
         string mycommand = "TVWISHLIST_QUICKMENU//TITLE//NAME";
         Log.Debug("Executing command " + mycommand);
         Main_GUI.Instance.Command(mycommand);
     }
     return true;
 }
        public IEnumerable<UniformInfo> GetActiveUniforms(IProgram program)
        {
            var uniforms = new List<UniformInfo>();

            var numberOfActiveUniforms = program.GetNumberOfActiveUniforms();
            for (var uniformIndex = 0; uniformIndex < numberOfActiveUniforms; uniformIndex++)
            {
                var uniform = GetActiveUniform(program.ProgramId, uniformIndex);
                uniforms.Add(uniform);
            }

            return uniforms;
        }
Exemplo n.º 10
0
		public PSSession(IDebugger debugger, IProgram program)
		{
			_program = program;
			var initialSessionState = InitialSessionState.CreateDefault();			
			initialSessionState.Variables.Add(new SessionStateVariableEntry("Debugger", debugger,
				"Interface to the Windows debuggers", ScopedItemOptions.Constant));
			initialSessionState.Variables.Add(new SessionStateVariableEntry("ShellID", "PSExt", "", ScopedItemOptions.Constant));
			var location = Assembly.GetExecutingAssembly().Location;
			initialSessionState.ImportPSModule(new []{location });
			var formatFile = Path.Combine(Path.GetDirectoryName(location), "PSExtCmdlets.Format.ps1xml");
			initialSessionState.Formats.Add(new SessionStateFormatEntry(formatFile));		
			_host = new DbgPsHost(debugger, program);
			_runspace = RunspaceFactory.CreateRunspace(_host, initialSessionState);
		}
Exemplo n.º 11
0
    //ILogger Log = ServiceRegistration.Get<ILogger>();
    public bool DoSomethingWithProgram(IProgram program)
    {
        Log.Debug("SlimTv Button Create TvWish was pressed");
        if (Main_GUI.Instance != null)
        {
            Main_GUI.Instance.Title(program.Title);
            Main_GUI.Instance.Name(program.Title);
            string mycommand = "NEWTVWISH//TITLE//NAME";
            Log.Debug("Executing command " + mycommand);
            Main_GUI.Instance.Command(mycommand);
            

        }
        return true;
    }
        public void Create()
        {
            var openGlResourceFactory = new OpenGlResourceFactory();
            var vertexShader = openGlResourceFactory.CreateShader(ShaderType.VertexShader);
            vertexShader.SetSource(VertexShaderSource);
            vertexShader.Compile();

            var fragmentShader = openGlResourceFactory.CreateShader(ShaderType.FragmentShader);
            fragmentShader.SetSource(FragmentShaderSource);
            fragmentShader.Compile();

            _program = openGlResourceFactory.CreateProgram();
            _program.Create();
            _program.AttachShader(vertexShader);
            _program.AttachShader(fragmentShader);
            _program.Link();
        }
Exemplo n.º 13
0
        public MainForm()
        {
            InitializeComponent();

            if (File.Exists(@"C:\OSP-P\VOLANTE\IMAGES\LATHE.DLL"))
            {
                _program = new LatheProgram();
            }
            else if (File.Exists(@"C:\OSP-P\VOLANTE\IMAGES\MC.DLL"))
            {
                _program = new MillProgram();
            }
            else
            {
                _program = new TestProgram();
            }
        }
Exemplo n.º 14
0
        public TerrainShader(IOpenGL33 gl)
        {
            vertexShader = new VertexShader(gl, GetEmbeddedResourceAsString("VertexShader.vs"));
            fragmentShader = new FragmentShader(gl, GetEmbeddedResourceAsString("FragmentShader.fs"));
            var p = new ModGL.ObjectModel.Shaders.Program(gl, vertexShader, fragmentShader);

            p.BindVertexAttributeLocations(PositionNormalTexCoord.Descriptor);
            // Bind output fragment to the specified nme
            gl.BindFragDataLocation(p.Handle, 0, "Color");
            // Compile program and shaders
            p.Compile();
            program = p;
            // Get the uniforms used by the shader program.
            diffuseUniform = p.GetUniform<Vector4fUniform, Vector4f>("DiffuseColor");
            modelViewProjection = p.GetUniform<MatrixUniform, Matrix4f>("ModelViewProjection");
            viewProjection = p.GetUniform<MatrixUniform, Matrix4f>("ViewProjection");
            textureUnitUniform = p.GetUniform<IntUniform, int>("Texture");
        }
Exemplo n.º 15
0
        public ConnectionManager(IProgram program, Rothko.IOperatingSystem os)
        {
            fileExists = (path) => os.File.Exists(path);
            readAllText = (path, encoding) => os.File.ReadAllText(path, encoding);
            writeAllText = (path, content) => os.File.WriteAllText(path, content);
            fileDelete = (path) => os.File.Delete(path);
            dirExists = (path) => os.Directory.Exists(path);
            dirCreate = (path) => os.Directory.CreateDirectory(path);

            Connections = new ObservableCollection<IConnection>();
            cachePath = System.IO.Path.Combine(
                os.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                program.ApplicationName,
                cacheFile);

            LoadConnectionsFromCache();

            Connections.CollectionChanged += RefreshConnections;
        }
Exemplo n.º 16
0
 public CubeShader(IOpenGL30 gl)
 {
     // Create the vertex shader
     vertexShader = new VertexShader(gl, GetEmbeddedResourceAsString("cube.vs"));
     // Create the fragmet shader
     fragmentShader = new FragmentShader(gl, GetEmbeddedResourceAsString("cube.fs"));
     // Create the program for both shaders
     var p = new ModGL.ObjectModel.Shaders.Program(gl, vertexShader, fragmentShader);
     // Tell the shader what field names to use (taken from the vertex Descriptor)
     p.BindVertexAttributeLocations(PositionNormalTexCoord.Descriptor);
     // Bind output fragment to the specified nme
     gl.BindFragDataLocation(p.Handle, 0, "Color");
     // Compile program and shaders
     p.Compile();
     program = p;
     // Get the uniforms used by the shader program.
     modelViewProjection = p.GetUniform<MatrixUniform, Matrix4f>("ModelViewProjection");
     viewProjection = p.GetUniform<MatrixUniform, Matrix4f>("ViewProjection");
     diffuseUniform = p.GetUniform<Vector4fUniform, Vector4f>("DiffuseColor");
 }
Exemplo n.º 17
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                using AutoResetEvent progressReportEvent = new AutoResetEvent(false);

                _shaderCount      = 0;
                _totalShaderCount = guestProgramList.Length;

                ShaderCacheStateChanged?.Invoke(ShaderCacheState.Start, _shaderCount, _totalShaderCount);
                Thread progressReportThread = null;

                if (guestProgramList.Length > 0)
                {
                    progressReportThread = new Thread(ReportProgress)
                    {
                        Name         = "ShaderCache.ProgressReporter",
                        Priority     = ThreadPriority.Lowest,
                        IsBackground = true
                    };

                    progressReportThread.Start(progressReportEvent);
                }

                // Make sure these are initialized before doing compilation.
                Capabilities caps = _context.Capabilities;

                int maxTaskCount = Math.Min(Environment.ProcessorCount, 8);
                int programIndex = 0;
                List <ShaderCompileTask> activeTasks = new List <ShaderCompileTask>();

                AutoResetEvent taskDoneEvent = new AutoResetEvent(false);

                // This thread dispatches tasks to do shader translation, and creates programs that OpenGL will link in the background.
                // The program link status is checked in a non-blocking manner so that multiple shaders can be compiled at once.

                while (programIndex < guestProgramList.Length || activeTasks.Count > 0)
                {
                    if (activeTasks.Count < maxTaskCount && programIndex < guestProgramList.Length)
                    {
                        // Begin a new shader compilation.
                        Hash128 key = guestProgramList[programIndex];

                        byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                        bool   hasHostCache      = hostProgramBinary != null;

                        IProgram hostProgram = null;

                        // If the program sources aren't in the cache, compile from saved guest program.
                        byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                        if (guestProgram == null)
                        {
                            Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                            // Should not happen, but if someone messed with the cache it's better to catch it.
                            invalidEntries?.Add(key);

                            _shaderCount = ++programIndex;

                            continue;
                        }

                        ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                        ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                        if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                        {
                            Debug.Assert(cachedShaderEntries.Length == 1);

                            GuestShaderCacheEntry entry = cachedShaderEntries[0];

                            HostShaderCacheEntry[] hostShaderEntries = null;

                            // Try loading host shader binary.
                            if (hasHostCache)
                            {
                                hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                                hostProgramBinary = hostProgramBinarySpan.ToArray();
                                hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                            }

                            ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
                            activeTasks.Add(task);

                            task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
                            {
                                ShaderProgram program = null;
                                ShaderProgramInfo shaderProgramInfo = null;

                                if (isHostProgramValid)
                                {
                                    // Reconstruct code holder.

                                    program           = new ShaderProgram(entry.Header.Stage, "");
                                    shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();

                                    ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                                    _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));

                                    return(true);
                                }
                                else
                                {
                                    // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.

                                    Task compileTask = Task.Run(() =>
                                    {
                                        IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                        program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
                                    });

                                    task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
                                    {
                                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                                        Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                                        // Compile shader and create program as the shader program binary got invalidated.
                                        shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
                                        hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                                        task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
                                        {
                                            // As the host program was invalidated, save the new entry in the cache.
                                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                                            if (!isReadOnly)
                                            {
                                                if (hasHostCache)
                                                {
                                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                                }
                                                else
                                                {
                                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                                }
                                            }

                                            _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));

                                            return(true);
                                        });

                                        return(false); // Not finished: still need to compile the host program.
                                    });

                                    return(false); // Not finished: translating the program.
                                }
                            });
                        }
                        else
                        {
                            Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                            ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                            List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                            TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);

                            TranslationFlags flags = DefaultFlags;

                            if (tfd != null)
                            {
                                flags |= TranslationFlags.Feedback;
                            }

                            TranslationCounts counts = new TranslationCounts();

                            HostShaderCacheEntry[] hostShaderEntries = null;

                            // Try loading host shader binary.
                            if (hasHostCache)
                            {
                                hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                                hostProgramBinary = hostProgramBinarySpan.ToArray();
                                hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                            }

                            ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
                            activeTasks.Add(task);

                            GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();

                            task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
                            {
                                Task compileTask = Task.Run(() =>
                                {
                                    // Reconstruct code holder.
                                    for (int i = 0; i < entries.Length; i++)
                                    {
                                        GuestShaderCacheEntry entry = entries[i];

                                        if (entry == null)
                                        {
                                            continue;
                                        }

                                        ShaderProgram program;

                                        if (entry.Header.SizeA != 0)
                                        {
                                            ShaderProgramInfo shaderProgramInfo;

                                            if (isHostProgramValid)
                                            {
                                                program           = new ShaderProgram(entry.Header.Stage, "");
                                                shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                            }
                                            else
                                            {
                                                IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                                TranslatorContext translatorContext  = Translator.CreateContext(0, gpuAccessor, flags, counts);
                                                TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, flags | TranslationFlags.VertexA, counts);

                                                program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
                                            }

                                            // NOTE: Vertex B comes first in the shader cache.
                                            byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                            byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                            shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                                        }
                                        else
                                        {
                                            ShaderProgramInfo shaderProgramInfo;

                                            if (isHostProgramValid)
                                            {
                                                program           = new ShaderProgram(entry.Header.Stage, "");
                                                shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                            }
                                            else
                                            {
                                                IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                                program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                            }

                                            shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                                        }

                                        shaderPrograms.Add(program);
                                    }
                                });

                                task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
                                {
                                    // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                                    if (!isHostProgramValid)
                                    {
                                        Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                                        List <IShader> hostShaders = new List <IShader>();

                                        // Compile shaders and create program as the shader program binary got invalidated.
                                        for (int stage = 0; stage < Constants.ShaderStages; stage++)
                                        {
                                            ShaderProgram program = shaders[stage]?.Program;

                                            if (program == null)
                                            {
                                                continue;
                                            }

                                            IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                                            shaders[stage].HostShader = hostShader;

                                            hostShaders.Add(hostShader);
                                        }

                                        hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                                        task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
                                        {
                                            // As the host program was invalidated, save the new entry in the cache.
                                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                                            if (!isReadOnly)
                                            {
                                                if (hasHostCache)
                                                {
                                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                                }
                                                else
                                                {
                                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                                }
                                            }

                                            _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));

                                            return(true);
                                        });

                                        return(false); // Not finished: still need to compile the host program.
                                    }
                                    else
                                    {
                                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));

                                        return(true);
                                    }
                                });

                                return(false); // Not finished: translating the program.
                            });
                        }

                        _shaderCount = ++programIndex;
                    }

                    // Process the queue.
                    for (int i = 0; i < activeTasks.Count; i++)
                    {
                        ShaderCompileTask task = activeTasks[i];

                        if (task.IsDone())
                        {
                            activeTasks.RemoveAt(i--);
                        }
                    }

                    if (activeTasks.Count == maxTaskCount)
                    {
                        // Wait for a task to be done, or for 1ms.
                        // Host shader compilation cannot signal when it is done,
                        // so the 1ms timeout is required to poll status.

                        taskDoneEvent.WaitOne(1);
                    }
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                progressReportEvent.Set();
                progressReportThread?.Join();

                ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);

                Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
            }
        }
Exemplo n.º 18
0
 public bool DoSomethingWithProgram(IProgram program)
 {
   return true;
 }
Exemplo n.º 19
0
        private static void HandleLine(string input, params string[] args)
        {
            if (currentProgram != null) //Check program
            {
                switch (input)
                {
                case "exit":        //Exit program
                case "stop":
                case "quit":
                    //Exit
                    currentProgram.Exit();
                    currentProgram = null;

                    //Clear
                    Console.Clear();
                    Console.WriteLine("Welcome to Abide Command Line");
                    break;

                default: currentProgram.OnInput(input, args); break;        //Program handle input
                }
            }
            else
            {
                switch (input)   //Handle input
                {
                case "clear":
                    Console.Clear();
                    Console.WriteLine("Welcome to Abide Command Line");
                    break;

                case "help":
                    Console.WriteLine("Yeah uhh no thanks.");
                    break;

                case "exit":
                case "stop":
                case "quit":
                    Program.input = false;
                    break;

                case "open":
                    Console.WriteLine("Drag map file... (Or type path)");
                    string filename = Console.ReadLine();
                    OpenMap(filename);
                    break;

                case "map":
                    if (selectedMap == null)
                    {
                        Console.WriteLine("No selected map."); return;
                    }
                    Console.WriteLine($"Selected map is {selectedMap.Name} ({selectedMap.Build})");
                    Console.WriteLine("Would you like to go to the editor? (Y/n)");
                    if (Console.ReadKey().Key == ConsoleKey.Y)
                    {
                        currentProgram = new MapEditor(selectedMap); currentProgram.Start();
                    }
                    break;

                default:
                    Console.WriteLine($"Unknown input: \"{input}\"");
                    break;
                }
            }
        }
Exemplo n.º 20
0
 public EnterpriseProbeTask(IProgram program, IHttpClient httpClient)
 {
     productHeader   = program.ProductHeader;
     this.httpClient = httpClient;
 }
        public bool RemoveSchedule(IProgram program)
        {
            Program indexProgram = program as Program;
              if (indexProgram == null)
            return false;

              if (!CheckConnection(indexProgram.ServerIndex))
            return false;

              WebResult result;
              try
              {
            result = TvServer(indexProgram.ServerIndex).CancelSchedule(program.ProgramId);
              }
              catch
              {
            return false;
              }
              return result.Result;
        }
Exemplo n.º 22
0
 protected virtual void UpdateProgramStatus(IProgram program)
 {
     CurrentProgram.SetProgram(program);
 }
Exemplo n.º 23
0
 public bool GetProgram(int programId, out IProgram program)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 24
0
 public bool GetProgram(int programId, out IProgram program)
 {
   throw new NotImplementedException();
 }
Exemplo n.º 25
0
 public ProgramEventArgs(IProgram program)
 {
     Program = program;
 }
Exemplo n.º 26
0
 public abstract Task <AsyncResult <ISchedule> > CreateScheduleAsync(IProgram program, ScheduleRecordingType recordingType);
Exemplo n.º 27
0
 public abstract Task <bool> RemoveScheduleForProgramAsync(IProgram program, ScheduleRecordingType recordingType);
Exemplo n.º 28
0
 public abstract bool GetProgram(int programId, out IProgram program);
Exemplo n.º 29
0
 public abstract Task <AsyncResult <IChannel> > GetChannelAsync(IProgram program);
Exemplo n.º 30
0
        protected virtual IProgram GetProgram(Mediaportal.TV.Server.TVDatabase.Entities.Program tvProgram, bool includeRecordingStatus = false)
#endif
        {
            InitGenreMap();

            //Convert to IProgram
            IProgram prog = tvProgram.ToProgram(includeRecordingStatus);

            if (prog == null)
            {
                return(null);
            }

            //Map genre color if possible
            if (_tvGenres.Count > 0 && !string.IsNullOrEmpty(prog.Genre))
            {
                var genre = _tvGenres.FirstOrDefault(g => g.Value.Any(e => prog.Genre.Equals(e, StringComparison.InvariantCultureIgnoreCase)));
                if (genre.Key != EpgGenre.Unknown)
                {
                    prog.EpgGenreId = (int)genre.Key;
                    switch (genre.Key)
                    {
                    case EpgGenre.Movie:
                        prog.EpgGenreColor = _epgColorSettings.MovieGenreColor;
                        break;

                    case EpgGenre.Series:
                        prog.EpgGenreColor = _epgColorSettings.SeriesGenreColor;
                        break;

                    case EpgGenre.Documentary:
                        prog.EpgGenreColor = _epgColorSettings.DocumentaryGenreColor;
                        break;

                    case EpgGenre.Music:
                        prog.EpgGenreColor = _epgColorSettings.MusicGenreColor;
                        break;

                    case EpgGenre.Kids:
                        prog.EpgGenreColor = _epgColorSettings.KidsGenreColor;
                        break;

                    case EpgGenre.News:
                        prog.EpgGenreColor = _epgColorSettings.NewsGenreColor;
                        break;

                    case EpgGenre.Sport:
                        prog.EpgGenreColor = _epgColorSettings.SportGenreColor;
                        break;

                    case EpgGenre.Special:
                        prog.EpgGenreColor = _epgColorSettings.SpecialGenreColor;
                        break;
                    }
                }
            }

            //If genre is unknown and the program contains series info, mark it as a series genre
            if (prog.EpgGenreId == (int)EpgGenre.Unknown &&
                (!string.IsNullOrWhiteSpace(tvProgram.SeriesNum) || !string.IsNullOrWhiteSpace(tvProgram.EpisodeNum) || !string.IsNullOrWhiteSpace(tvProgram.EpisodePart)))
            {
                prog.EpgGenreId    = (int)EpgGenre.Series;
                prog.EpgGenreColor = _epgColorSettings.SeriesGenreColor;
            }
            return(prog);
        }
Exemplo n.º 31
0
        protected void ShowProgramActions(IProgram program)
        {
            if (program == null)
            {
                return;
            }

            ILocalization loc = ServiceRegistration.Get <ILocalization>();

            _programActions = new ItemsList();
            // if program is over already, there is nothing to do.
            if (program.EndTime < DateTime.Now)
            {
                _programActions.Add(new ListItem(Consts.KEY_NAME, loc.ToString("[SlimTvClient.ProgramOver]")));
            }
            else
            {
                // Check if program is currently running.
                bool isRunning = DateTime.Now >= program.StartTime && DateTime.Now <= program.EndTime;
                if (isRunning)
                {
                    _programActions.Add(new ListItem(Consts.KEY_NAME, loc.ToString("[SlimTvClient.WatchNow]"))
                    {
                        Command = new MethodDelegateCommand(() =>
                        {
                            IChannel channel;
                            if (_tvHandler.ProgramInfo.GetChannel(program, out channel))
                            {
                                IWorkflowManager workflowManager = ServiceRegistration.Get <IWorkflowManager>();
                                SlimTvClientModel model          = workflowManager.GetModel(SlimTvClientModel.MODEL_ID) as SlimTvClientModel;
                                if (model != null)
                                {
                                    model.Tune(channel);
                                    // Always switch to fullscreen
                                    workflowManager.NavigatePush(Consts.WF_STATE_ID_FULLSCREEN_VIDEO);
                                }
                            }
                        })
                    });
                }

                if (_tvHandler.ScheduleControl != null)
                {
                    RecordingStatus recordingStatus;
                    if (_tvHandler.ScheduleControl.GetRecordingStatus(program, out recordingStatus) && recordingStatus != RecordingStatus.None)
                    {
                        if (isRunning)
                        {
                            _programActions.Add(
                                new ListItem(Consts.KEY_NAME, loc.ToString("[SlimTvClient.WatchFromBeginning]"))
                            {
                                Command = new MethodDelegateCommand(() => _tvHandler.WatchRecordingFromBeginning(program))
                            });
                        }

                        _programActions.Add(
                            new ListItem(Consts.KEY_NAME, loc.ToString(isRunning ? "[SlimTvClient.StopCurrentRecording]" : "[SlimTvClient.DeleteSchedule]", program.Title))
                        {
                            Command = new MethodDelegateCommand(() =>
                            {
                                if (_tvHandler.ScheduleControl.RemoveScheduleForProgram(program, ScheduleRecordingType.Once))
                                {
                                    UpdateRecordingStatus(program, RecordingStatus.None);
                                }
                            }
                                                                )
                        });
                    }
                    else
                    {
                        _programActions.Add(
                            new ListItem(Consts.KEY_NAME, loc.ToString(isRunning ? "[SlimTvClient.RecordNow]" : "[SlimTvClient.CreateSchedule]"))
                        {
                            Command = new MethodDelegateCommand(() =>
                            {
                                ISchedule schedule;
                                bool result;
                                // "No Program" placeholder
                                if (program.ProgramId == -1)
                                {
                                    result = _tvHandler.ScheduleControl.CreateScheduleByTime(new Channel {
                                        ChannelId = program.ChannelId
                                    }, program.StartTime, program.EndTime, out schedule);
                                }
                                else
                                {
                                    result = _tvHandler.ScheduleControl.CreateSchedule(program, ScheduleRecordingType.Once, out schedule);
                                }

                                if (result)
                                {
                                    UpdateRecordingStatus(program, RecordingStatus.Scheduled);
                                }
                            }
                                                                )
                        });
                    }
                }
            }

            // Add list entries for extensions
            foreach (KeyValuePair <Guid, TvExtension> programExtension in _programExtensions)
            {
                TvExtension extension = programExtension.Value;
                // First check if this extension applies for the selected program
                if (!extension.Extension.IsAvailable(program))
                {
                    continue;
                }

                _programActions.Add(
                    new ListItem(Consts.KEY_NAME, loc.ToString(extension.Caption))
                {
                    Command = new MethodDelegateCommand(() => extension.Extension.ProgramAction(program))
                });
            }

            IScreenManager screenManager = ServiceRegistration.Get <IScreenManager>();

            screenManager.ShowDialog(_programActionsDialogName);
        }
Exemplo n.º 32
0
 public VertexStreamRL VertexStreamRL(IProgram program)
 {
     return(bufferRangeRL.VertexStreamRL(program));
 }
Exemplo n.º 33
0
 protected virtual bool UpdateRecordingStatus(IProgram program)
 {
     return(true);
 }
Exemplo n.º 34
0
        /// <summary>
        /// L2 error of some quantity derived from the state vector (e.g.,
        /// entropy) with respect to given reference solution. The quadrature
        /// is determined from the settings in <see cref="IBMControl"/>
        /// </summary>
        /// <param name="quantityOfInterest"></param>
        /// <param name="referenceSolution"></param>
        /// <returns></returns>
        public static Query L2Error(Func <StateVector, double> quantityOfInterest, Func <double[], double, double> referenceSolution)
        {
            return(delegate(IApplication <AppControl> app, double time) {
                IProgram <CNSControl> program = app as IProgram <CNSControl>;
                if (program == null)
                {
                    throw new Exception();
                }

                ImmersedSpeciesMap speciesMap = program.SpeciesMap as ImmersedSpeciesMap;
                IBMControl control = program.Control as IBMControl;
                if (speciesMap == null || control == null)
                {
                    throw new Exception(
                        "Query is only valid for immersed boundary runs");
                }

                SpeciesId species = speciesMap.Tracker.GetSpeciesId(control.FluidSpeciesName);
                int order = control.LevelSetQuadratureOrder;
                CellQuadratureScheme scheme = speciesMap.QuadSchemeHelper.GetVolumeQuadScheme(
                    species, true, speciesMap.SubGrid.VolumeMask);
                var composititeRule = scheme.Compile(program.GridData, order);
                IChunkRulePair <QuadRule>[] chunkRulePairs = composititeRule.ToArray();

                DGField density = program.WorkingSet.Density;
                VectorField <DGField> momentum = program.WorkingSet.Momentum;
                DGField energy = program.WorkingSet.Energy;

                // Construct dummy field since L2Error is currently only supported
                // for Field's; However, _avoid_ a projection.
                DGField dummy = new SinglePhaseField(new Basis(program.GridData, 0));
                Material material = speciesMap.GetMaterial(double.NaN);
                int index = 0;
                double value = dummy.LxError(
                    (ScalarFunctionEx) delegate(int j0, int Len, NodeSet nodes, MultidimensionalArray result) {
                    MultidimensionalArray input = program.GridData.GlobalNodes.GetValue_Cell(nodes, j0, Len);

                    Chunk chunk = chunkRulePairs[index].Chunk;
                    QuadRule rule = chunkRulePairs[index].Rule;

                    if (chunk.i0 != j0 || chunk.Len != Len)
                    {
                        throw new Exception();
                    }

                    if (rule.NoOfNodes != nodes.GetLength(0))
                    {
                        throw new Exception();
                    }

                    MultidimensionalArray rho = MultidimensionalArray.Create(chunk.Len, rule.NoOfNodes);
                    density.Evaluate(chunk.i0, chunk.Len, nodes, rho);

                    MultidimensionalArray[] m = new MultidimensionalArray[CompressibleEnvironment.NumberOfDimensions];
                    for (int d = 0; d < CompressibleEnvironment.NumberOfDimensions; d++)
                    {
                        m[d] = MultidimensionalArray.Create(chunk.Len, rule.NoOfNodes);
                        momentum[d].Evaluate(chunk.i0, chunk.Len, nodes, m[d]);
                    }

                    MultidimensionalArray rhoE = MultidimensionalArray.Create(chunk.Len, rule.NoOfNodes);
                    energy.Evaluate(chunk.i0, chunk.Len, nodes, rhoE);

                    double[] X = new double[CompressibleEnvironment.NumberOfDimensions];
                    Vector mVec = new Vector(CompressibleEnvironment.NumberOfDimensions);
                    for (int i = 0; i < chunk.Len; i++)
                    {
                        for (int j = 0; j < rule.NoOfNodes; j++)
                        {
                            for (int d = 0; d < CompressibleEnvironment.NumberOfDimensions; d++)
                            {
                                X[d] = input[i, j, d];
                                mVec[d] = m[d][i, j];
                            }

                            StateVector state = new StateVector(material, rho[i, j], mVec, rhoE[i, j]);
                            double qoi = quantityOfInterest(state);

                            Debug.Assert(
                                !double.IsNaN(qoi),
                                "Encountered node with unphysical state"
                                + " (not able to determine quantity of interest)");

                            result[i, j] = qoi - referenceSolution(X, time);
                        }
                    }

                    index++;
                },
                    (X, a, b) => (a - b) * (a - b),
                    composititeRule);

                // No value is NaN, but the results. How can this be?
                // => All values around 0, but values in void region are a little
                // farther away from the exact solution
                // => weights in the void zone sum up to something slightly negative
                Debug.Assert(
                    value >= 0,
                    "Encountered unphysical norm even though individual values where valid."
                    + " This indicates a problem with cut-cell quadrature.");

                return Math.Sqrt(value);
            });
        }
Exemplo n.º 35
0
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)

        {
            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            log.Info(jsonContent);

            if (data.channelName == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                    error = "Please pass channelName in the input object"
                }));
            }
            if (data.programName == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                    error = "Please pass programName in the input object"
                }));
            }
            string   channelName = data.channelName;
            string   programName = data.programName;
            IProgram program     = null;

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();

            log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                log.Info("Context object created.");

                var channel = _context.Channels.Where(c => c.Name == channelName).FirstOrDefault();
                if (channel == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new
                    {
                        error = string.Format("Channel {0} not found", channelName)
                    }));
                }

                program = channel.Programs.Where(p => p.Name.Equals(programName)).FirstOrDefault();
                if (program == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new
                    {
                        error = string.Format("Program {0} not found", programName)
                    }));
                }
                var asset = program.Asset;

                log.Info("Deleting program...");
                program.Delete();
                log.Info("Program deleted.");

                if (data.deleteAsset != null && (bool)data.deleteAsset)
                {
                    log.Info("Deleting asset...");
                    asset.Delete();
                    log.Info("Asset deleted.");
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message }));
            }

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                success = true
            }));
        }
Exemplo n.º 36
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="patch"></param>
 public WindowEditSingleProgram(IProgram patch)
 {
     InitializeComponent();
     _patch = patch;
 }
Exemplo n.º 37
0
 public async Task <AsyncResult <IChannel> > GetChannelAsync(IProgram program)
 {
     return(await GetChannelAsync(program.ChannelId));
 }
Exemplo n.º 38
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="clipBoardPatches"></param>
 /// <param name="patch1"></param>
 /// <param name="overwriteAllowed"></param>
 /// <returns></returns>
 private bool CheckOverwriteAllowedForPrograms(out IClipBoardPatches clipBoardPatches, IProgram patch1,
                                               bool overwriteAllowed)
 {
     clipBoardPatches = null;
     if (((IBank)(patch1.Parent)).IsWritable &&
         (Settings.Default.CopyPaste_OverwriteFilledPrograms || patch1.IsEmptyOrInit))
     {
         IProgram program = patch1;
         clipBoardPatches = PcgClipBoard.Programs[(int)(((IProgramBank)(program.Parent)).BankSynthesisType)];
         overwriteAllowed = true;
     }
     return(overwriteAllowed);
 }
Exemplo n.º 39
0
        public bool GetNextProgram(IChannel channel, out IProgram program)
        {
            IProgram programNow;

            return(GetNowNextProgram(channel, out programNow, out program));
        }
        public bool GetNextProgram(IChannel channel, out IProgram program)
        {
            program = null;

              Channel indexChannel = channel as Channel;
              if (indexChannel == null)
            return false;

              if (!CheckConnection(indexChannel.ServerIndex))
            return false;

              IProgram currentProgram;
              try
              {
            if (GetCurrentProgram(channel, out currentProgram))
            {
              IList<WebProgramDetailed> nextPrograms = TvServer(indexChannel.ServerIndex).GetProgramsDetailedForChannel(channel.ChannelId,
                                                                                          currentProgram.EndTime.AddMinutes(1),
                                                                                          currentProgram.EndTime.AddMinutes(1));
              if (nextPrograms != null && nextPrograms.Count > 0)
              {
            program = new Program(nextPrograms[0], indexChannel.ServerIndex);
            return true;
              }
            }
              }
              catch (Exception ex)
              {
            ServiceRegistration.Get<ILogger>().Error(ex.Message);
              }
              return false;
        }
Exemplo n.º 41
0
 public bool RemoveScheduleForProgram(IProgram program, ScheduleRecordingType recordingType)
 {
   try
   {
     CpAction action = GetAction(Consts.ACTION_REMOVE_SCHEDULE_FOR_PROGRAM);
     IList<object> inParameters = new List<object> { program.ProgramId, (int)recordingType };
     IList<object> outParameters = action.InvokeAction(inParameters);
     return (bool)outParameters[0];
   }
   catch (Exception ex)
   {
     NotifyException(ex);
     return false;
   }
 }
Exemplo n.º 42
0
        public AddIn(InteropApplication application, IProgram program, IRibbon ribbon)
        {
            this.Application = application;
            this.Program     = program;
            this.Ribbon      = ribbon;

            this.workbookByInteropWorkbook = new Dictionary <InteropWorkbook, Workbook>();

            ((InteropAppEvents_Event)this.Application).NewWorkbook += async interopWorkbook =>
            {
                if (!string.IsNullOrWhiteSpace(this.ExistentialAttribute))
                {
                    var customProperties = new CustomProperties(interopWorkbook.CustomDocumentProperties);
                    if (!customProperties.Exist(this.ExistentialAttribute))
                    {
                        return;
                    }
                }

                var workbook = this.New(interopWorkbook);
                for (var i = 1; i <= interopWorkbook.Worksheets.Count; i++)
                {
                    var interopWorksheet = (InteropWorksheet)interopWorkbook.Worksheets[i];
                    workbook.New(interopWorksheet);
                }

                var worksheets = workbook.Worksheets;
                await this.Program.OnNew(workbook);

                foreach (var worksheet in worksheets)
                {
                    await program.OnNew(worksheet);
                }
            };

            this.Application.WorkbookOpen += async interopWorkbook =>
            {
                if (!string.IsNullOrWhiteSpace(this.ExistentialAttribute))
                {
                    var customProperties = new CustomProperties(interopWorkbook.CustomDocumentProperties);
                    if (!customProperties.Exist(this.ExistentialAttribute))
                    {
                        return;
                    }
                }

                var workbook = this.New(interopWorkbook);
                for (var i = 1; i <= interopWorkbook.Worksheets.Count; i++)
                {
                    var interopWorksheet = (InteropWorksheet)interopWorkbook.Worksheets[i];
                    workbook.New(interopWorksheet);
                }

                var worksheets = workbook.Worksheets;
                await this.Program.OnNew(workbook);

                foreach (var worksheet in worksheets)
                {
                    await program.OnNew(worksheet);
                }
            };

            this.Application.WorkbookActivate += interopWorkbook =>
            {
                if (!string.IsNullOrWhiteSpace(this.ExistentialAttribute))
                {
                    var customProperties = new CustomProperties(interopWorkbook.CustomDocumentProperties);
                    if (!customProperties.Exist(this.ExistentialAttribute))
                    {
                        return;
                    }
                }

                if (!this.WorkbookByInteropWorkbook.TryGetValue(interopWorkbook, out var workbook))
                {
                    workbook = this.New(interopWorkbook);
                }

                workbook.IsActive = true;
            };

            this.Application.WorkbookDeactivate += wb =>
            {
                // Could already be gone by the WorkbookBeforeClose event
                if (this.WorkbookByInteropWorkbook.TryGetValue(wb, out _))
                {
                    this.WorkbookByInteropWorkbook[wb].IsActive = false;
                }
            };

            void WorkbookBeforeClose(InteropWorkbook interopWorkbook, ref bool cancel)
            {
                if (this.WorkbookByInteropWorkbook.TryGetValue(interopWorkbook, out var workbook))
                {
                    this.Program.OnClose(workbook, ref cancel);
                    if (!cancel)
                    {
                        this.Close(interopWorkbook);
                    }
                }
            }

            this.Application.WorkbookBeforeClose += WorkbookBeforeClose;
        }
Exemplo n.º 43
0
 public bool GetRecordingFileOrStream(IProgram program, out string fileOrStream)
 {
   try
   {
     CpAction action = GetAction(Consts.ACTION_GET_REC_FILE_OR_STREAM);
     IList<object> inParameters = new List<object> { program.ProgramId };
     IList<object> outParameters = action.InvokeAction(inParameters);
     bool result = (bool)outParameters[0];
     fileOrStream = (string)outParameters[1];
     return result;
   }
   catch (Exception ex)
   {
     NotifyException(ex);
     fileOrStream = null;
     return false;
   }
 }
        public bool GetChannel(IProgram program, out IChannel channel)
        {
            channel = null;
              Program indexProgram = program as Program;
              if (indexProgram == null)
            return false;

              if (!CheckConnection(indexProgram.ServerIndex))
            return false;

              try
              {
            WebChannelBasic tvChannel = TvServer(indexProgram.ServerIndex).GetChannelBasicById(indexProgram.ChannelId);
            if (tvChannel != null)
            {
              channel = new Channel { ChannelId = tvChannel.Id, Name = tvChannel.DisplayName, ServerIndex = indexProgram.ServerIndex };
              return true;
            }
              }
              catch (Exception ex)
              {
            ServiceRegistration.Get<ILogger>().Error(ex.Message);
              }
              return false;
        }
Exemplo n.º 45
0
 public abstract Task <AsyncResult <RecordingStatus> > GetRecordingStatusAsync(IProgram program);
Exemplo n.º 46
0
        public bool GetCurrentProgram(IChannel channel, out IProgram program)
        {
            IProgram programNext;

            return(GetNowNextProgram(channel, out program, out programNext));
        }
Exemplo n.º 47
0
 public bool CreateSchedule(IProgram program, ScheduleRecordingType recordingType, out ISchedule schedule)
 {
   try
   {
     CpAction action = GetAction(Consts.ACTION_CREATE_SCHEDULE);
     IList<object> inParameters = new List<object> { program.ProgramId, (int) recordingType };
     IList<object> outParameters = action.InvokeAction(inParameters);
     bool result = (bool)outParameters[0];
     schedule = result ? (ISchedule)outParameters[1] : null;
     return result;
   }
   catch (Exception ex)
   {
     NotifyException(ex);
     schedule = null;
     return false;
   }
 }
Exemplo n.º 48
0
 public abstract Task <AsyncResult <string> > GetRecordingFileOrStreamAsync(IProgram program);
Exemplo n.º 49
0
 public bool GetRecordingStatus(IProgram program, out RecordingStatus recordingStatus)
 {
   try
   {
     CpAction action = GetAction(Consts.ACTION_GET_REC_STATUS);
     IList<object> inParameters = new List<object> { program.ProgramId };
     IList<object> outParameters = action.InvokeAction(inParameters);
     bool result = (bool)outParameters[0];
     recordingStatus = (RecordingStatus)Enum.Parse(typeof(RecordingStatus), outParameters[1].ToString());
     return result;
   }
   catch (Exception ex)
   {
     NotifyException(ex);
     recordingStatus = RecordingStatus.None;
     return false;
   }
 }
Exemplo n.º 50
0
        protected override bool UpdateRecordingStatus(IProgram program, RecordingStatus newStatus)
        {
            bool changed = base.UpdateRecordingStatus(program, newStatus);

            return(changed && UpdateRecordingStatus(program));
        }
        public bool CreateSchedule(IProgram program)
        {
            Program indexProgram = program as Program;
              if (indexProgram == null)
            return false;

              if (!CheckConnection(indexProgram.ServerIndex))
            return false;

              WebResult result;
              try
              {
            result = TvServer(indexProgram.ServerIndex).AddSchedule(program.ChannelId, program.Title, program.StartTime,
                                                       program.EndTime, WebScheduleType.Once);
              }
              catch
              {
            return false;
              }
              return result.Result;
        }
        private static MediaProgram GetProgramDetails(IProgram program)
        {
            var programDetails = EntityFactory.BuildProgramFromIProgram(program);

            return(programDetails);
        }
        public bool GetCurrentProgram(IChannel channel, out IProgram program)
        {
            program = null;

              Channel indexChannel = channel as Channel;
              if (indexChannel == null)
            return false;

              if (!CheckConnection(indexChannel.ServerIndex))
            return false;

              try
              {
            WebProgramDetailed tvProgram = TvServer(indexChannel.ServerIndex).GetCurrentProgramOnChannel(channel.ChannelId);
            if (tvProgram != null)
            {
              program = new Program(tvProgram, indexChannel.ServerIndex);
              return true;
            }
              }
              catch (Exception ex)
              {
            ServiceRegistration.Get<ILogger>().Error(ex.Message);
              }
              return false;
        }
Exemplo n.º 54
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
                {
                    Hash128 key = guestProgramList[programIndex];

                    Logger.Info?.Print(LogClass.Gpu, $"Compiling shader {key} ({programIndex + 1} / {guestProgramList.Length})");

                    byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                    bool   hasHostCache      = hostProgramBinary != null;

                    IProgram hostProgram = null;

                    // If the program sources aren't in the cache, compile from saved guest program.
                    byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                    if (guestProgram == null)
                    {
                        Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                        // Should not happen, but if someone messed with the cache it's better to catch it.
                        invalidEntries?.Add(key);

                        continue;
                    }

                    ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                    ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                    if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                    {
                        Debug.Assert(cachedShaderEntries.Length == 1);

                        GuestShaderCacheEntry entry = cachedShaderEntries[0];

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        ShaderProgram     program;
                        ShaderProgramInfo shaderProgramInfo;

                        // Reconstruct code holder.
                        if (isHostProgramValid)
                        {
                            program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                            shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
                        }
                        else
                        {
                            IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                            program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
                        }

                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (hostProgram == null)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            // Compile shader and create program as the shader program binary got invalidated.
                            shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
                            hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
                    }
                    else
                    {
                        Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                        ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                        List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                        TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformationFeedbackInformations(ref guestProgramReadOnlySpan, fileHeader);

                        TranslationFlags flags = DefaultFlags;

                        if (tfd != null)
                        {
                            flags = TranslationFlags.Feedback;
                        }

                        TranslationCounts counts = new TranslationCounts();

                        HostShaderCacheEntry[] hostShaderEntries = null;

                        // Try loading host shader binary.
                        if (hasHostCache)
                        {
                            hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                            hostProgramBinary = hostProgramBinarySpan.ToArray();
                            hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                        }

                        bool isHostProgramValid = hostProgram != null;

                        // Reconstruct code holder.
                        for (int i = 0; i < cachedShaderEntries.Length; i++)
                        {
                            GuestShaderCacheEntry entry = cachedShaderEntries[i];

                            if (entry == null)
                            {
                                continue;
                            }

                            ShaderProgram program;

                            if (entry.Header.SizeA != 0)
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext((ulong)entry.Header.Size, 0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                // NOTE: Vertex B comes first in the shader cache.
                                byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                            }
                            else
                            {
                                ShaderProgramInfo shaderProgramInfo;

                                if (isHostProgramValid)
                                {
                                    program           = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
                                    shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                }
                                else
                                {
                                    IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                    program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
                                }

                                shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                            }

                            shaderPrograms.Add(program);
                        }

                        // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                        if (!isHostProgramValid)
                        {
                            Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                            List <IShader> hostShaders = new List <IShader>();

                            // Compile shaders and create program as the shader program binary got invalidated.
                            for (int stage = 0; stage < Constants.ShaderStages; stage++)
                            {
                                ShaderProgram program = shaders[stage]?.Program;

                                if (program == null)
                                {
                                    continue;
                                }

                                IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                                shaders[stage].HostShader = hostShader;

                                hostShaders.Add(hostShader);
                            }

                            hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                            // As the host program was invalidated, save the new entry in the cache.
                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                            if (!isReadOnly)
                            {
                                if (hasHostCache)
                                {
                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                }
                                else
                                {
                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                }
                            }
                        }

                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
                    }
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                Logger.Info?.Print(LogClass.Gpu, "Shader cache loaded.");
            }
        }
        public bool GetRecordingStatus(IProgram program, out RecordingStatus recordingStatus)
        {
            recordingStatus = RecordingStatus.None;

              Program indexProgram = program as Program;
              if (indexProgram == null)
            return false;

              if (!CheckConnection(indexProgram.ServerIndex))
            return false;

              try
              {
            WebProgramDetailed programDetailed = TvServer(indexProgram.ServerIndex).GetProgramDetailedById(program.ProgramId);
            recordingStatus = Program.GetRecordingStatus(programDetailed);
              }
              catch
              {
            return false;
              }
              return true;
        }
Exemplo n.º 56
0
        private static void CreateProgramListItem(IProgram program, ListItem itemToUpdate, IProgram previousProgram = null)
        {
            ProgramListItem item = itemToUpdate as ProgramListItem;

            if (item == null)
            {
                return;
            }
            item.Program.SetProgram(program ?? GetNoProgram(previousProgram));
            item.AdditionalProperties["PROGRAM"] = program;
            item.Update();
        }
Exemplo n.º 57
0
    /// <summary>
    /// Tries to update a program item, i.e. if recording status was changed.
    /// </summary>
    /// <param name="program">Program</param>
    private void UpdateProgramStatus(IProgram program)
    {
      if (program == null)
        return;
      FrameworkElement control = Children.FirstOrDefault(el =>
      {
        ProgramProperties programProperties = ((ProgramListItem)el.Context).Program;
        return programProperties != null && programProperties.ProgramId == program.ProgramId;
      });
      if (control == null)
        return;

      // Update properties
      IProgramRecordingStatus recordingStatus = program as IProgramRecordingStatus;
      if (recordingStatus != null)
        ((ProgramListItem)control.Context).Program.IsScheduled = recordingStatus.RecordingStatus != RecordingStatus.None;
    }
Exemplo n.º 58
0
        /// <summary>
        /// Gets a compute shader from the cache.
        /// </summary>
        /// <remarks>
        /// This automatically translates, compiles and adds the code to the cache if not present.
        /// </remarks>
        /// <param name="state">Current GPU state</param>
        /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
        /// <param name="localSizeX">Local group size X of the computer shader</param>
        /// <param name="localSizeY">Local group size Y of the computer shader</param>
        /// <param name="localSizeZ">Local group size Z of the computer shader</param>
        /// <param name="localMemorySize">Local memory size of the compute shader</param>
        /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
        /// <returns>Compiled compute shader code</returns>
        public ShaderBundle GetComputeShader(
            GpuState state,
            ulong gpuVa,
            int localSizeX,
            int localSizeY,
            int localSizeZ,
            int localMemorySize,
            int sharedMemorySize)
        {
            bool isCached = _cpPrograms.TryGetValue(gpuVa, out List <ShaderBundle> list);

            if (isCached)
            {
                foreach (ShaderBundle cachedCpShader in list)
                {
                    if (IsShaderEqual(cachedCpShader, gpuVa))
                    {
                        return(cachedCpShader);
                    }
                }
            }

            TranslatorContext[] shaderContexts = new TranslatorContext[1];

            shaderContexts[0] = DecodeComputeShader(
                state,
                gpuVa,
                localSizeX,
                localSizeY,
                localSizeZ,
                localMemorySize,
                sharedMemorySize);

            bool isShaderCacheEnabled  = _cacheManager != null;
            bool isShaderCacheReadOnly = false;

            Hash128 programCodeHash = default;

            GuestShaderCacheEntry[] shaderCacheEntries = null;

            // Current shader cache doesn't support bindless textures
            if (shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless))
            {
                isShaderCacheEnabled = false;
            }

            if (isShaderCacheEnabled)
            {
                isShaderCacheReadOnly = _cacheManager.IsReadOnly;

                // Compute hash and prepare data for shader disk cache comparison.
                shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
                programCodeHash    = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
            }

            ShaderBundle cpShader;

            // Search for the program hash in loaded shaders.
            if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
            {
                if (isShaderCacheEnabled)
                {
                    Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
                }

                // The shader isn't currently cached, translate it and compile it.
                ShaderCodeHolder shader = TranslateShader(shaderContexts[0]);

                shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);

                IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                hostProgram.CheckProgramLink(true);

                byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                cpShader = new ShaderBundle(hostProgram, shader);

                if (isShaderCacheEnabled)
                {
                    _cpProgramsDiskCache.Add(programCodeHash, cpShader);

                    if (!isShaderCacheReadOnly)
                    {
                        _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
                    }
                }
            }

            if (!isCached)
            {
                list = new List <ShaderBundle>();

                _cpPrograms.Add(gpuVa, list);
            }

            list.Add(cpShader);

            return(cpShader);
        }
Exemplo n.º 59
0
 public bool IsAvailable (IProgram program)
 {
   return true;
 }
Exemplo n.º 60
0
        /// <summary>
        /// Gets a graphics shader program from the shader cache.
        /// This includes all the specified shader stages.
        /// </summary>
        /// <remarks>
        /// This automatically translates, compiles and adds the code to the cache if not present.
        /// </remarks>
        /// <param name="state">Current GPU state</param>
        /// <param name="addresses">Addresses of the shaders for each stage</param>
        /// <returns>Compiled graphics shader code</returns>
        public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
        {
            bool isCached = _gpPrograms.TryGetValue(addresses, out List <ShaderBundle> list);

            if (isCached)
            {
                foreach (ShaderBundle cachedGpShaders in list)
                {
                    if (IsShaderEqual(cachedGpShaders, addresses))
                    {
                        return(cachedGpShaders);
                    }
                }
            }

            TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];

            TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);

            TranslationFlags flags = DefaultFlags;

            if (tfd != null)
            {
                flags |= TranslationFlags.Feedback;
            }

            TranslationCounts counts = new TranslationCounts();

            if (addresses.VertexA != 0)
            {
                shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
            }

            shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
            shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
            shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
            shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
            shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);

            bool isShaderCacheEnabled  = _cacheManager != null;
            bool isShaderCacheReadOnly = false;

            Hash128 programCodeHash = default;

            GuestShaderCacheEntry[] shaderCacheEntries = null;

            // Current shader cache doesn't support bindless textures
            for (int i = 0; i < shaderContexts.Length; i++)
            {
                if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
                {
                    isShaderCacheEnabled = false;
                    break;
                }
            }

            if (isShaderCacheEnabled)
            {
                isShaderCacheReadOnly = _cacheManager.IsReadOnly;

                // Compute hash and prepare data for shader disk cache comparison.
                shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
                programCodeHash    = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
            }

            ShaderBundle gpShaders;

            // Search for the program hash in loaded shaders.
            if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
            {
                if (isShaderCacheEnabled)
                {
                    Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
                }

                // The shader isn't currently cached, translate it and compile it.
                ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];

                shaders[0] = TranslateShader(shaderContexts[1], shaderContexts[0]);
                shaders[1] = TranslateShader(shaderContexts[2]);
                shaders[2] = TranslateShader(shaderContexts[3]);
                shaders[3] = TranslateShader(shaderContexts[4]);
                shaders[4] = TranslateShader(shaderContexts[5]);

                List <IShader> hostShaders = new List <IShader>();

                for (int stage = 0; stage < Constants.ShaderStages; stage++)
                {
                    ShaderProgram program = shaders[stage]?.Program;

                    if (program == null)
                    {
                        continue;
                    }

                    IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);

                    shaders[stage].HostShader = hostShader;

                    hostShaders.Add(hostShader);
                }

                IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                hostProgram.CheckProgramLink(true);

                byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                gpShaders = new ShaderBundle(hostProgram, shaders);

                if (isShaderCacheEnabled)
                {
                    _gpProgramsDiskCache.Add(programCodeHash, gpShaders);

                    if (!isShaderCacheReadOnly)
                    {
                        _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
                    }
                }
            }

            if (!isCached)
            {
                list = new List <ShaderBundle>();

                _gpPrograms.Add(addresses, list);
            }

            list.Add(gpShaders);

            return(gpShaders);
        }