Example #1
0
File: Ssao.cs Project: ylyking/Myre
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define settings
            var settings = renderer.Settings;
            //settings.Add("ssao_enabled", "Determines if Screen Space Ambient Occlusion is enabled.", true);
            //settings.Add("ssao_halfres", "Determines if SSAO will run at full of half screen resolution.", true);
            settings.Add("ssao_radius", "SSAO sample radius", 1f);
            settings.Add("ssao_intensity", "SSAO intensity", 2.5f);
            settings.Add("ssao_scale", "Scales distance between occluders and occludee.", 1f);
            //settings.Add("ssao_detailradius", "SSAO sample radius", 2.3f);
            //settings.Add("ssao_detailintensity", "SSAO intensity", 15f);
            //settings.Add("ssao_detailscale", "Scales distance between occluders and occludee.", 1.5f);
            settings.Add("ssao_blur", "The amount to blur SSAO.", 1f);
            //settings.Add("ssao_radiosityintensity", "The intensity of local radiosity colour transfer.", 0.0f);
            settings.Add("ssao_highquality", "Switches between high and low quality SSAO sampling pattern.", false);

            // define inputs
            context.DefineInput("gbuffer_depth_downsample");
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");

            if (context.AvailableResources.Any(r => r.Name == "edges"))
                context.DefineInput("edges");

            // define outputs
            context.DefineOutput("ssao");

            base.Initialise(renderer, context);
        }
Example #2
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define inputs
            context.DefineInput("gbuffer_depth");   //used implicitly with GBUFFER_DEPTH semantic

            base.Initialise(renderer, context);
        }
Example #3
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _quad = new Quad(renderer.Device);

            //Create geometry management objects
            _geometryProviders = renderer.Scene.FindManagers<IGeometryProvider>();
            _depthPeeler = new DepthPeel();

            var settings = renderer.Settings;

            // 1 - Min
            // 5 - Default
            // 10 - Extreme
            settings.Add("transparency_deferred_layers", "the max number of depth peeled layers to use for deferred transparency", 5);

            //Make sure deferred lighting is enabled
            LightingComponent.SetupScene(renderer.Scene, out _directLights, out _indirectLights);

            // define inputs
            context.DefineInput("gbuffer_depth");
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");
            context.DefineInput("lightbuffer");

            //define outputs
            context.DefineOutput("gbuffer_depth");
            context.DefineOutput("lightbuffer", isLeftSet: true, surfaceFormat: SurfaceFormat.HdrBlendable, depthFormat: DepthFormat.Depth24Stencil8);

            base.Initialise(renderer, context);
        }
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define outputs
            context.DefineOutput("gbuffer_depth", isLeftSet: false, surfaceFormat: SurfaceFormat.Single, depthFormat: DepthFormat.Depth24Stencil8);
            context.DefineOutput("gbuffer_normals", isLeftSet: false, surfaceFormat: SurfaceFormat.Rgba1010102);
            context.DefineOutput("gbuffer_diffuse", isLeftSet: false, surfaceFormat: SurfaceFormat.Color);
            context.DefineOutput("gbuffer_depth_downsample", isLeftSet: true, surfaceFormat: SurfaceFormat.Single);

            base.Initialise(renderer, context);
        }
Example #5
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define inputs
            context.DefineInput("gbuffer_depth");

            // define outputs
            foreach (var resource in context.SetRenderTargets)
                context.DefineOutput(resource);

            base.Initialise(renderer, context);
        }
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _inputs = Inputs(context).ToArray();
            foreach (var input in _inputs)
                context.DefineInput(input.ResourceName);

            _output = Output();
            context.DefineOutput(_output, true);

            base.Initialise(renderer, context);
        }
Example #7
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _geometry = new GeometryRenderer(renderer.Scene.FindManagers<IGeometryProvider>());

            // define outputs
            context.DefineOutput("gbuffer_depth", isLeftSet: false, surfaceFormat: SurfaceFormat.Single, depthFormat: DepthFormat.Depth24Stencil8);
            context.DefineOutput("gbuffer_normals", isLeftSet: false, surfaceFormat: SurfaceFormat.Rgba1010102);
            context.DefineOutput("gbuffer_diffuse", isLeftSet: false, surfaceFormat: SurfaceFormat.Color);
            context.DefineOutput("gbuffer_depth_downsample", isLeftSet: true, surfaceFormat: SurfaceFormat.Single);

            base.Initialise(renderer, context);
        }
Example #8
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _decalManager = renderer.Scene.GetManager<Decal.Manager>();

            // define inputs
            context.DefineInput("gbuffer_depth");       //Used implicitly by the shader (using the GBUFFER_DEPTH semantic)

            // define outputs
            context.DefineOutput("decal_normals");
            context.DefineOutput("decal_diffuse");

            base.Initialise(renderer, context);
        }
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define inputs
            if (inputResource == null)
                inputResource = context.SetRenderTargets[0].Name;

            context.DefineInput(inputResource);
            context.DefineInput("edges");

            // define outputs
            context.DefineOutput("antialiased", isLeftSet: true, surfaceFormat: SurfaceFormat.Color);

            base.Initialise(renderer, context);
        }
Example #10
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _geometryProviders = renderer.Scene.FindManagers<IGeometryProvider>();

            // define inputs
            if (context.AvailableResources.Any(r => r.Name == "gbuffer_depth"))
                context.DefineInput("gbuffer_depth");

            // define outputs
            foreach (var resource in context.SetRenderTargets)
                context.DefineOutput(resource);

            base.Initialise(renderer, context);
        }
Example #11
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _mixDecalMaterial = new Material(Content.Load<Effect>("DecalBufferMix").Clone(), "MixDecalBuffers");
            _quad = new Quad(renderer.Device);

            // define inputs
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");
            context.DefineInput("decal_normals");
            context.DefineInput("decal_diffuse");

            // define outputs
            context.DefineOutput("gbuffer_normals");
            context.DefineOutput("gbuffer_diffuse");

            base.Initialise(renderer, context);
        }
Example #12
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define inputs
            context.DefineInput("gbuffer_depth");
            context.DefineInput("gbuffer_normals");

            // define outputs
            context.DefineOutput("edges", isLeftSet: true, surfaceFormat: SurfaceFormat.Color);

            // define settings
            var settings = renderer.Settings;
            settings.Add("edge_normalthreshold", "Threshold used to decide between an edge and a non-edge by normal.", 0.5f);
            settings.Add("edge_depththreshold", "Threshold used to decide between an edge and a non-edge by depth.", 0.01f);
            settings.Add("edge_normalweight", "Weighting used for edges detected via normals in the output.", 0.15f);
            settings.Add("edge_depthweight", "Weighting used for edges detected via depth in the output.", 0.2f);

            base.Initialise(renderer, context);
        }
Example #13
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            _quad = new Quad(renderer.Device);

            // define inputs
            if (_inputResource == null)
                _inputResource = context.SetRenderTargets[0].Name;
            
            context.DefineInput(_inputResource);

            // define outputs
            context.DefineOutput("antialiased", isLeftSet: true, surfaceFormat: SurfaceFormat.Color);

            // define settings
            var settings = renderer.Settings;

            //   1.00 - upper limit (softer)
            //   0.75 - default amount of filtering
            //   0.50 - lower limit (sharper, less sub-pixel aliasing removal)
            //   0.25 - almost off
            //   0.00 - completely off
            settings.Add("fxaa_subpixelaliasingremoval", "the amount of sub-pixel aliasing removal. This can effect sharpness.", 0.75f);

            //   0.333 - too little (faster)
            //   0.250 - low quality
            //   0.166 - default
            //   0.125 - high quality 
            //   0.063 - overkill (slower)
            settings.Add("fxaa_edgethreshold", "The minimum amount of local contrast required to apply algorithm.", 0.166f);

            //   0.0833 - upper limit (default, the start of visible unfiltered edges)
            //   0.0625 - high quality (faster)
            //   0.0312 - visible limit (slower)
            // Special notes when using FXAA_GREEN_AS_LUMA,
            //   Likely want to set this to zero.
            //   As colors that are mostly not-green
            //   will appear very dark in the green channel!
            //   Tune by looking at mostly non-green content,
            //   then start at zero and increase until aliasing is a problem.
            settings.Add("fxaa_edgethresholdmin", "Trims the algorithm from processing darks.", 0.0f);

            base.Initialise(renderer, context);
        }
Example #14
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define inputs
            context.DefineInput("gbuffer_depth");
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");

            if (context.AvailableResources.Any(r => r.Name == "ssao"))
                context.DefineInput("ssao");

            // define outputs
            context.DefineOutput("lightbuffer", isLeftSet:true, surfaceFormat:SurfaceFormat.HdrBlendable, depthFormat:DepthFormat.Depth24Stencil8);
            context.DefineOutput("directlighting", isLeftSet:false, surfaceFormat: SurfaceFormat.HdrBlendable, depthFormat: DepthFormat.Depth24Stencil8);

            // Setup light managers and find lists of all lights
            SetupScene(renderer.Scene, out _directLights, out _indirectLights);

            base.Initialise(renderer, context);
        }
Example #15
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define settings
            var settings = renderer.Settings;
            settings.Add("ssao_radius", "SSAO sample radius", 1f);
            settings.Add("ssao_intensity", "SSAO intensity", 2.5f);
            settings.Add("ssao_scale", "Scales distance between occluders and occludee.", 1f);
            settings.Add("ssao_blur", "The amount to blur SSAO.", 1f);

            // define inputs
            context.DefineInput("gbuffer_depth_downsample");
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");

            if (context.AvailableResources.Any(r => r.Name == "edges"))
                context.DefineInput("edges");

            // define outputs
            context.DefineOutput("ssao");

            base.Initialise(renderer, context);
        }
Example #16
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define settings
            var settings = renderer.Settings;
            settings.Add("hdr_adaptionrate", "The rate at which the cameras' exposure adapts to changes in the scene luminance.", 1f);
            settings.Add("hdr_bloomthreshold", "The under-exposure applied during bloom thresholding.", 6f);
            settings.Add("hdr_bloommagnitude", "The overall brightness of the bloom effect.", 3f);
            settings.Add("hdr_bloomblurammount", "The amount to blur the bloom target.", 2.2f);
            settings.Add("hdr_minexposure", "The minimum exposure the camera can adapt to.", -1.1f);
            settings.Add("hdr_maxexposure", "The maximum exposure the camera can adapt to.", 1.1f);

            // define inputs
            context.DefineInput("lightbuffer");

            // define outputs
            //context.DefineOutput("luminancemap", isLeftSet: false, width: 1024, height: 1024, surfaceFormat: SurfaceFormat.Single);
            context.DefineOutput("luminance", isLeftSet: false, width: 1, height: 1, surfaceFormat: SurfaceFormat.Single);
            context.DefineOutput("bloom", isLeftSet: false, surfaceFormat: SurfaceFormat.Rgba64);
            context.DefineOutput("tonemapped", isLeftSet: true, surfaceFormat: SurfaceFormat.Color, depthFormat: DepthFormat.Depth24Stencil8);
            
            base.Initialise(renderer, context);
        }
Example #17
0
        public QueryLayer(ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            ResourceContext = resourceContext;
        }
        void window_Load(object sender, EventArgs e)
        {
            this.GraphicsContext = new DebugGraphicsContext(new OpenGLGraphicsContext());
            var locator = new ServiceLocator();
            locator.RegisterService<IGraphicsContext>(this.GraphicsContext);

            var resourceLoader = new ResourceLoader();
            resourceLoader.AddImportersAndProcessors(typeof(ResourceLoader).Assembly);

            this.Resourses = new ResourceContext(locator, new TypeReaderFactory(), new TypeWriterFactory(), resourceLoader,
                                                        Path.Combine(this.resourceFolder, "Assets"), this.resourceFolder);
            this.Resourses.ShouldSaveAllLoadedAssets = false;

            pixel = this.Resourses.LoadAsset<TextureAtlas>("Fonts\\Metro_W_Pixel.atlas")["pixel"];
            var effect = this.Resourses.LoadAsset<ShaderProgram>("Basic.effect");
            this.spriteBuffer = new SpriteBuffer(this.GraphicsContext, effect);
            this.guiRenderer = new GUIRenderer(this.spriteBuffer, pixel);

            window.VSync = VSyncMode.Off;
            window.Keyboard.KeyRepeat = true;

            // Other state
            GraphicsContext.Enable(EnableCap.Blend);
            GraphicsContext.Enable(EnableCap.ScissorTest);
            GraphicsContext.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);

            var factory = CreateGUIFactory();
            this.Load(factory);

            clock = new Clock();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataSerializerContext"/> class.
 /// </summary>
 /// <param name="resource">The resource whose property is being nested.</param>
 /// <param name="selectExpandClause">The <see cref="SelectExpandClause"/> for the property being nested.</param>
 /// <param name="edmProperty">The complex property being nested or the navigation property being expanded.
 /// If the resource property is the dynamic complex, the resource property is null.
 /// </param>
 /// <remarks>This constructor is used to construct the serializer context for writing nested and expanded properties.</remarks>
 public ODataSerializerContext(ResourceContext resource, SelectExpandClause selectExpandClause, IEdmProperty edmProperty)
     : this(resource, edmProperty, null, null)
 {
     SelectExpandClause = selectExpandClause;
 }
        public override ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, ResourceContext resourceContext)
        {
            ODataProperty property = base.CreateStructuralProperty(structuralProperty, resourceContext);

            var instance = resourceContext.ResourceInstance;
            var parent   = resourceContext.SerializerContext.ExpandedResource;

            if (parent != null)
            {
                var parentInstance = parent.ResourceInstance;
            }

            return(property);
        }
        public IDictionary <ResourceFieldAttribute, QueryLayer> GetSecondaryProjectionForRelationshipEndpoint(ResourceContext secondaryResourceContext)
        {
            var secondaryIdAttribute = secondaryResourceContext.Attributes.Single(a => a.Property.Name == nameof(Identifiable.Id));
            var sparseFieldSet       = new SparseFieldSetExpression(new[] { secondaryIdAttribute });

            var secondaryProjection = GetSparseFieldSetProjection(new[] { sparseFieldSet }, secondaryResourceContext) ?? new Dictionary <ResourceFieldAttribute, QueryLayer>();

            secondaryProjection[secondaryIdAttribute] = null;

            return(secondaryProjection);
        }
Example #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ManageController"/> class.
 /// </summary>
 /// <param name="resourceContext">The resource context.</param>
 public ManageController(ResourceContext resourceContext)
 {
     _resources = resourceContext;
 }
Example #23
0
 public async Task UpdateAsync(ResourceContext context)
 {
     NullCheck.ThrowIfNull <ResourceContext>(context);
     context.consumable.Update(this);
     await context.SaveChangesAsync();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataSerializerContext"/> class for nested resources.
        /// </summary>
        /// <param name="resource">The resource whose property is being nested.</param>
        /// <param name="edmProperty">The complex property being nested or the navigation property being expanded.
        /// If the resource property is the dynamic complex, the resource property is null.
        /// </param>
        /// <param name="queryContext">The <see cref="ODataQueryContext"/> for the property being nested.</param>
        /// <param name="currentSelectItem">The <see cref="SelectItem"/> for the property being nested.></param>
        internal ODataSerializerContext(ResourceContext resource, IEdmProperty edmProperty, ODataQueryContext queryContext, SelectItem currentSelectItem)
        {
            if (resource == null)
            {
                throw Error.ArgumentNull("resource");
            }

            // Clone the resource's context. Use a helper function so it can
            // handle platform-specific differences in ODataSerializerContext.
            ODataSerializerContext context = resource.SerializerContext;

            this.CopyPlatformSpecificProperties(context);

            Model           = context.Model;
            Path            = context.Path;
            RootElementName = context.RootElementName;
            SkipExpensiveAvailabilityChecks = context.SkipExpensiveAvailabilityChecks;
            MetadataLevel   = context.MetadataLevel;
            Items           = context.Items;
            ExpandReference = context.ExpandReference;

            QueryContext = queryContext;

            ExpandedResource = resource; // parent resource

            CurrentSelectItem = currentSelectItem;

            var expandedNavigationSelectItem = currentSelectItem as ExpandedNavigationSelectItem;

            if (expandedNavigationSelectItem != null)
            {
                SelectExpandClause = expandedNavigationSelectItem.SelectAndExpand;
                NavigationSource   = expandedNavigationSelectItem.NavigationSource;
            }
            else
            {
                var pathSelectItem = currentSelectItem as PathSelectItem;
                if (pathSelectItem != null)
                {
                    SelectExpandClause = pathSelectItem.SelectAndExpand;
                    NavigationSource   = resource.NavigationSource; // Use it's parent navigation source.
                }

                var referencedNavigation = currentSelectItem as ExpandedReferenceSelectItem;
                if (referencedNavigation != null)
                {
                    ExpandReference  = true;
                    NavigationSource = referencedNavigation.NavigationSource;
                }
            }

            EdmProperty = edmProperty; // should be nested property

            if (currentSelectItem == null || (NavigationSource as IEdmUnknownEntitySet) != null)
            {
                IEdmNavigationProperty navigationProperty = edmProperty as IEdmNavigationProperty;
                if (navigationProperty != null && context.NavigationSource != null)
                {
                    NavigationSource = context.NavigationSource.FindNavigationTarget(NavigationProperty);
                }
                else
                {
                    NavigationSource = resource.NavigationSource;
                }
            }
        }
 public ResourceService(ResourceContext applicationContext, IEventBus eventBus)
 {
     _applicationContext = applicationContext;
     _eventBus = eventBus;
 }
Example #26
0
        public IReadOnlyCollection <ResourceFieldAttribute> GetSparseFieldSetForQuery(ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            if (!_visitedTable.ContainsKey(resourceContext))
            {
                SparseFieldSetExpression inputExpression = _lazySourceTable.Value.ContainsKey(resourceContext)
                    ? new SparseFieldSetExpression(_lazySourceTable.Value[resourceContext])
                    : null;

                SparseFieldSetExpression outputExpression = _resourceDefinitionAccessor.OnApplySparseFieldSet(resourceContext.ResourceType, inputExpression);

                HashSet <ResourceFieldAttribute> outputFields = outputExpression == null
                    ? new HashSet <ResourceFieldAttribute>()
                    : outputExpression.Fields.ToHashSet();

                _visitedTable[resourceContext] = outputFields;
            }

            return(_visitedTable[resourceContext]);
        }
Example #27
0
        public IReadOnlyCollection <AttrAttribute> GetIdAttributeSetForRelationshipQuery(ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            AttrAttribute idAttribute     = resourceContext.Attributes.Single(attr => attr.Property.Name == nameof(Identifiable.Id));
            var           inputExpression = new SparseFieldSetExpression(idAttribute.AsArray());

            // Intentionally not cached, as we are fetching ID only (ignoring any sparse fieldset that came from query string).
            SparseFieldSetExpression outputExpression = _resourceDefinitionAccessor.OnApplySparseFieldSet(resourceContext.ResourceType, inputExpression);

            HashSet <AttrAttribute> outputAttributes = outputExpression == null
                ? new HashSet <AttrAttribute>()
                : outputExpression.Fields.OfType <AttrAttribute>().ToHashSet();

            outputAttributes.Add(idAttribute);
            return(outputAttributes);
        }
Example #28
0
        public IReadOnlyCollection <ResourceFieldAttribute> GetSparseFieldSetForSerializer(ResourceContext resourceContext)
        {
            ArgumentGuard.NotNull(resourceContext, nameof(resourceContext));

            if (!_visitedTable.ContainsKey(resourceContext))
            {
                HashSet <ResourceFieldAttribute> inputFields = _lazySourceTable.Value.ContainsKey(resourceContext)
                    ? _lazySourceTable.Value[resourceContext]
                    : GetResourceFields(resourceContext);

                var inputExpression = new SparseFieldSetExpression(inputFields);
                SparseFieldSetExpression outputExpression = _resourceDefinitionAccessor.OnApplySparseFieldSet(resourceContext.ResourceType, inputExpression);

                HashSet <ResourceFieldAttribute> outputFields;

                if (outputExpression == null)
                {
                    outputFields = GetResourceFields(resourceContext);
                }
                else
                {
                    outputFields = new HashSet <ResourceFieldAttribute>(inputFields);
                    outputFields.IntersectWith(outputExpression.Fields);
                }

                _visitedTable[resourceContext] = outputFields;
            }

            return(_visitedTable[resourceContext]);
        }
Example #29
0
 public ErrorChecking(ErrorContext errors, ResourceContext resources)
 {
     _errors    = errors;
     _resources = resources;
 }
Example #30
0
        /// <summary>
        /// Executes the resource.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="parameters">The parameters.</param>
        /// <exception cref="System.ArgumentNullException">Throws an exception if either parameter is <c>null</c>.</exception>
        public void ExecuteResource(string resourceName, ResourceParameters parameters)
        {
            if (string.IsNullOrEmpty(resourceName))
            {
                throw new ArgumentNullException("resourceName");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            string message;
            var    logger  = Configuration.Logger;
            var    context = new ResourceResultContext(logger, Configuration.FrameworkProvider, Configuration.Serializer, Configuration.HtmlEncoder);

            // First we determine the current policy as it has been processed so far
            RuntimePolicy policy = DetermineAndStoreAccumulatedRuntimePolicy(RuntimeEvent.ExecuteResource);

            // It is possible that the policy now says Off, but if the requested resource is the default resource, then we need to make sure
            // there is a good reason for not executing that resource, since the default resource is the one we most likely need to set
            // Glimpse On in the first place.
            if (resourceName.Equals(Configuration.DefaultResource.Name))
            {
                // To be clear we only do this for the default resource, and we do this because it allows us to secure the default resource the same way
                // as any other resource, but for this we only rely on runtime policies that handle ExecuteResource runtime events and we ignore
                // ignore previously executed runtime policies (most likely during BeginRequest).
                // Either way, the default runtime policy is still our starting point and when it says Off, it remains Off
                policy = DetermineRuntimePolicy(RuntimeEvent.ExecuteResource, Configuration.DefaultRuntimePolicy);
            }

            if (policy == RuntimePolicy.Off)
            {
                string errorMessage = string.Format(Resources.ExecuteResourceInsufficientPolicy, resourceName);
                logger.Info(errorMessage);
                new StatusCodeResourceResult(403, errorMessage).Execute(context);
                return;
            }

            var resources =
                Configuration.Resources.Where(
                    r => r.Name.Equals(resourceName, StringComparison.InvariantCultureIgnoreCase));

            IResourceResult result;

            switch (resources.Count())
            {
            case 1:     // 200 - OK
                try
                {
                    var resource        = resources.First();
                    var resourceContext = new ResourceContext(parameters.GetParametersFor(resource), Configuration.PersistenceStore, logger);

                    var privilegedResource = resource as IPrivilegedResource;

                    if (privilegedResource != null)
                    {
                        result = privilegedResource.Execute(resourceContext, Configuration);
                    }
                    else
                    {
                        result = resource.Execute(resourceContext);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(Resources.GlimpseRuntimeExecuteResourceError, ex, resourceName);
                    result = new ExceptionResourceResult(ex);
                }

                break;

            case 0:     // 404 - File Not Found
                message = string.Format(Resources.ExecuteResourceMissingError, resourceName);
                logger.Warn(message);
                result = new StatusCodeResourceResult(404, message);
                break;

            default:     // 500 - Server Error
                message = string.Format(Resources.ExecuteResourceDuplicateError, resourceName);
                logger.Warn(message);
                result = new StatusCodeResourceResult(500, message);
                break;
            }

            try
            {
                result.Execute(context);
            }
            catch (Exception exception)
            {
                logger.Fatal(Resources.GlimpseRuntimeExecuteResourceResultError, exception, result.GetType());
            }
        }
 public ResourceTableViewComponent(ResourceContext context)
 {
     _context = context;
 }
        private SortExpression GetSort(string parameterValue, ResourceFieldChainExpression scope)
        {
            ResourceContext resourceContextInScope = GetResourceContextForScope(scope);

            return(_sortParser.Parse(parameterValue, resourceContextInScope));
        }
        private async void tsLocation_Toggled(object sender, RoutedEventArgs e)
        {
            _settings.IsLocationActivated = tsLocation.IsOn;

            if (tsLocation.IsOn && _geo == null)
            {
                // Initialise GeoLocator
                var access = await Geolocator.RequestAccessAsync();

                switch (access)
                {
                case GeolocationAccessStatus.Allowed:
                    _geo = new Geolocator();
                    _geo.DesiredAccuracy = PositionAccuracy.Default;

                    tblLocationError.Text = "";
                    break;

                default:
                    // There was a problem initialising GeoLocator
                    // Show an error to the user
                    ResourceCandidate resource = ResourceManager.Current.MainResourceMap.GetValue("Resources/uidLocationError", ResourceContext.GetForCurrentView());
                    tblLocationError.Text = resource.ValueAsString;

                    // Turn off location toggle
                    tsLocation.IsOn = false;
                    break;
                }
            }

            // Update settings file
            Storage.SaveSettingsInIsoStorage(_settings);
        }
Example #34
0
 /// <summary>
 /// Creates a new instance of <see cref="NetworkInterfaceBuilder"/>
 /// </summary>
 /// <param name="name"></param>
 public NetworkInterfaceBuilder(string name, ResourceContext context) : base(name, context)
 {
 }
Example #35
0
 public async Task <IFindable> FindAsync(ResourceContext context, int id)
 {
     NullCheck.ThrowIfNull <ResourceContext>(context);
     return(await context.consumable.FindAsync(id));
 }
Example #36
0
        private FilterExpression GetFilter(string parameterValue, ResourceFieldChainExpression scope)
        {
            ResourceContext resourceContextInScope = GetResourceContextForScope(scope);

            return(_filterParser.Parse(parameterValue, resourceContextInScope));
        }
Example #37
0
        // Obtain instances of the Resource Map and Resource Context provided by
        // the Windows Modern Resource Manager (MRM).

        // Not thread-safe. Only call this once on one thread for each object instance.
        // For example, System.Runtime.ResourceManager only calls this from its constructors,
        // guaranteeing that this only gets called once, on one thread, for each new instance
        // of System.Runtime.ResourceManager.

        // Throws exceptions
        // Only returns true if the function succeeded completely.
        // Outputs exceptionInfo since it may be needed for debugging purposes
        // if an exception is thrown by one of Initialize's callees.
        public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo)
        {
            Debug.Assert(libpath != null);
            Debug.Assert(reswFilename != null);
            exceptionInfo = null;

            if (InitializeStatics())
            {
                // AllResourceMaps can throw ERROR_MRM_MAP_NOT_FOUND,
                // although in that case we are not sure for which package it failed to find
                // resources (if we are looking for resources for a framework package,
                // it might throw ERROR_MRM_MAP_NOT_FOUND if the app package
                // resources could not be loaded, even if the framework package
                // resources are properly configured). So we will not fill in the
                // exceptionInfo structure at this point since we don't have any
                // reliable information to include in it.

                IReadOnlyDictionary <string, ResourceMap>
                resourceMapDictionary = s_globalResourceManager.AllResourceMaps;

                if (resourceMapDictionary != null)
                {
                    string packageSimpleName = FindPackageSimpleNameForFilename(libpath);

#if netstandard
                    // If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that
                    // an application may have packaged in its AppX. This is to enforce AppX apps to use PRI resources.
                    if (packageSimpleName != null)
                    {
                        if (packageSimpleName.EndsWith(".resources.dll", StringComparison.CurrentCultureIgnoreCase))
                        {
                            // Pretend we didn't get a package name. When an attempt is made to get resource string, GetString implementation
                            // will see that we are going to use modern resource manager but we don't have PRI and will thrown an exception indicating
                            // so. This will force the developer to have a valid PRI based resource.
                            packageSimpleName = null;
                        }
                    }
#endif //  netstandard
                    if (packageSimpleName != null)
                    {
                        ResourceMap packageResourceMap = null;

                        // Win8 enforces that package simple names are unique (for example, the App Store will not
                        // allow two apps with the same package simple name). That is why the Modern Resource Manager
                        // keys access to resources based on the package simple name.
                        if (resourceMapDictionary.TryGetValue(packageSimpleName, out packageResourceMap))
                        {
                            if (packageResourceMap != null)
                            {
                                // GetSubtree returns null when it cannot find resource strings
                                // named "reswFilename/*" for the package we are looking up.

                                reswFilename = UriUtility.UriEncode(reswFilename);
                                _resourceMap = packageResourceMap.GetSubtree(reswFilename);

                                if (_resourceMap == null)
                                {
                                    exceptionInfo = new PRIExceptionInfo();
                                    exceptionInfo.PackageSimpleName = packageSimpleName;
                                    exceptionInfo.ResWFile          = reswFilename;
                                }
                                else
                                {
                                    _clonedResourceContext = s_globalResourceContext.Clone();

                                    if (_clonedResourceContext != null)
                                    {
                                        // Will need to be changed the first time it is used. But we can't set it to "" since we will take a lock on it.
                                        _clonedResourceContextFallBackList = ReadOnlyListToString(_clonedResourceContext.Languages);

                                        if (_clonedResourceContextFallBackList != null)
                                        {
                                            return(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
Example #38
0
 public async Task DeleteAsync(ResourceContext context)
 {
     NullCheck.ThrowIfNull <ResourceContext>(context);
     context.demand_consumable.Remove(this);
     await context.SaveChangesAsync();
 }
Example #39
0
 protected void ValidateSingleRelationship(RelationshipAttribute relationship, ResourceContext resourceContext, string path)
 {
     if (!relationship.CanInclude)
     {
         throw new InvalidQueryStringParameterException(_lastParameterName,
                                                        "Including the requested relationship is not allowed.",
                                                        path == relationship.PublicName
                 ? $"Including the relationship '{relationship.PublicName}' on '{resourceContext.PublicName}' is not allowed."
                 : $"Including the relationship '{relationship.PublicName}' in '{path}' on '{resourceContext.PublicName}' is not allowed.");
     }
 }
Example #40
0
        /// <summary>
        /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
        /// tag will invoke this when they are recognized by Cortana, passing along details of the
        /// invocation.
        ///
        /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must
        /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
        /// input). There is no execution time limit on the background task managed by Cortana,
        /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
        /// on the Cortana app package in order to prevent Cortana timing out the task during
        /// debugging.
        ///
        /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
        /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
        /// in order to debug background task behaviors. In order to debug background tasks, open the
        /// project properties for the app package (not the background task project), and enable
        /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
        /// initial progress screen, and attach to the background task process while it executes.
        /// </summary>
        /// <param name="taskInstance">Connection to the hosting background service process.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            // This should match the uap:AppService and VoiceCommandService references from the
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any
                    // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc
                    // prior to calling this will produce undefined behavior.
                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    // Depending on the operation (defined in ConferenceRoom:ConferenceRoomCommands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                    case "":

                        break;

                    case "openPPTback":
                        await PPoint();

                        break;

                    default:
                        // As with app activation VCDs, we need to handle the possibility that
                        // an app update may remove a voice command that is still registered.
                        // This can happen if the user hasn't run an app since an update.
                        LaunchAppInForeground();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
Example #41
0
 private static extern IntPtr Scenes_makeEditor(
     [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(NativeClassMarshaler))] ResourceContext resourceContext);
Example #42
0
        public override void Initialise(Renderer renderer, ResourceContext context)
        {
            // define inputs
            context.DefineInput("gbuffer_depth");
            context.DefineInput("gbuffer_normals");
            context.DefineInput("gbuffer_diffuse");
            //context.DefineInput("gbuffer_depth_downsample");

            if (context.AvailableResources.Any(r => r.Name == "ssao"))
                context.DefineInput("ssao");

            // define outputs
            context.DefineOutput("lightbuffer", isLeftSet:true, surfaceFormat:SurfaceFormat.HdrBlendable, depthFormat:DepthFormat.Depth24Stencil8);
            context.DefineOutput("directlighting", isLeftSet:false, surfaceFormat: SurfaceFormat.HdrBlendable, depthFormat: DepthFormat.Depth24Stencil8);

            // define default light managers
            var scene = renderer.Scene;
            scene.GetManager<DeferredAmbientLightManager>();
            scene.GetManager<DeferredPointLightManager>();
            scene.GetManager<DeferredSkyboxManager>();
            scene.GetManager<DeferredSpotLightManager>();
            scene.GetManager<DeferredSunLightManager>();

            // get lights
            _directLights = scene.FindManagers<IDirectLight>();
            _indirectLights = scene.FindManagers<IIndirectLight>();

            base.Initialise(renderer, context);
        }
        /// <inheritdoc />
        public QueryLayer WrapLayerForSecondaryEndpoint <TId>(QueryLayer secondaryLayer, ResourceContext primaryResourceContext, TId primaryId, RelationshipAttribute secondaryRelationship)
        {
            var innerInclude = secondaryLayer.Include;

            secondaryLayer.Include = null;

            var primaryIdAttribute = primaryResourceContext.Attributes.Single(x => x.Property.Name == nameof(Identifiable.Id));
            var sparseFieldSet     = new SparseFieldSetExpression(new[] { primaryIdAttribute });

            var primaryProjection = GetSparseFieldSetProjection(new[] { sparseFieldSet }, primaryResourceContext) ?? new Dictionary <ResourceFieldAttribute, QueryLayer>();

            primaryProjection[secondaryRelationship] = secondaryLayer;
            primaryProjection[primaryIdAttribute]    = null;

            return(new QueryLayer(primaryResourceContext)
            {
                Include = RewriteIncludeForSecondaryEndpoint(innerInclude, secondaryRelationship),
                Filter = CreateFilterById(primaryId, primaryResourceContext),
                Projection = primaryProjection
            });
        }
Example #44
0
        private RelationshipAttribute GetExistingRelationship(AtomicReference reference, ResourceContext resourceContext)
        {
            RelationshipAttribute relationship = resourceContext.Relationships.FirstOrDefault(attribute => attribute.PublicName == reference.Relationship);

            if (relationship == null)
            {
                throw new JsonApiSerializationException("The referenced relationship does not exist.",
                                                        $"Resource of type '{reference.Type}' does not contain a relationship named '{reference.Relationship}'.",
                                                        atomicOperationIndex: AtomicOperationIndex);
            }

            return(relationship);
        }
        protected virtual IReadOnlyCollection <IncludeElementExpression> GetIncludeElements(IReadOnlyCollection <IncludeElementExpression> includeElements, ResourceContext resourceContext)
        {
            if (resourceContext == null)
            {
                throw new ArgumentNullException(nameof(resourceContext));
            }

            var resourceDefinition = _resourceDefinitionProvider.Get(resourceContext.ResourceType);

            if (resourceDefinition != null)
            {
                includeElements = resourceDefinition.OnApplyIncludes(includeElements);
            }

            return(includeElements);
        }
Example #46
0
 protected new abstract IEnumerable<InputBinding> Inputs(ResourceContext context);
Example #47
0
        private void ValidateSingleDataForRelationship(ResourceObject dataResourceObject, ResourceContext resourceContext, string elementPath)
        {
            AssertElementHasType(dataResourceObject, elementPath);
            AssertElementHasIdOrLid(dataResourceObject, elementPath, true);

            ResourceContext resourceContextInData = GetExistingResourceContext(dataResourceObject.Type);

            AssertCompatibleType(resourceContextInData, resourceContext, elementPath);
            AssertCompatibleId(dataResourceObject, resourceContextInData.IdentityType);
        }
Example #48
0
 public ResourceRepository()
 {
     _ctx = new ResourceContext();
 }
Example #49
0
        public SamePage()
        {
            InitializeComponent();

            _applicationTrigger = new ApplicationTrigger();

            if (IsTypePresent != null)
            {
                IsTypePresent.Text =
                    $"ApiInformation.IsTypePresent Windows.Phone.UI.Input.HardwareButtons = {ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")}";
            }

            ResourceContext resourceContext = ResourceContext.GetForCurrentView();
            List <string>   _ = resourceContext.QualifierValues.Keys.ToList();

            Loaded += async(sender, args) =>
            {
                BackgroundTaskRegistration backgroundTaskRegistration = await RegisterBackgroudTask(_applicationTrigger);

                if (backgroundTaskRegistration != null)
                {
                    backgroundTaskRegistration.Progress += delegate(BackgroundTaskRegistration registration, BackgroundTaskProgressEventArgs eventArgs)
                    {
                        // ReSharper disable once UnusedVariable
                        IAsyncAction ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            BackgroundTextBlock.Text = eventArgs.Progress.ToString();
                        });
                    };
                    backgroundTaskRegistration.Completed += (registration, eventArgs) =>
                    {
                        // ReSharper disable once UnusedVariable
                        IAsyncAction ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            BackgroundTextBlock.Text = "Completed";
                        });
                    };
                }

                if (MinSizeTExtBlock != null)
                {
                    Window currentWindow = Window.Current;
                    MinSizeTExtBlock.Text      = $"{currentWindow.Bounds.Width} x {currentWindow.Bounds.Height}";
                    currentWindow.SizeChanged += (o, eventArgs) =>
                    {
                        Size eventArgsSize = eventArgs.Size;
                        MinSizeTExtBlock.Text = $"{eventArgsSize.Width} x {eventArgsSize.Height}";
                    };
                }

                DataTransferManager t = DataTransferManager.GetForCurrentView();
                t.DataRequested += (dataSender, dataRequestedEventArgs) =>
                {
                    DataPackage r = dataRequestedEventArgs.Request.Data;
                    r.Properties.ApplicationName = "Stoca";
                    r.Properties.Description     = "stoca description";
                    r.Properties.Title           = "Stoca title";
                    r.SetText("stoca shared");
                };
                t.ShareProvidersRequested += (dataSender, shareProvidersRequestedEventArgs) =>
                {
                };
                t.TargetApplicationChosen += (dataSender, targetApplicationChosenEventArgs) =>
                {
                };
            };

            Unloaded += (sender, args) =>
            {
                IList <VisualStateGroup> visualStateGroups = VisualStateManager.GetVisualStateGroups((FrameworkElement)Content);

                IEnumerable <OrientationStateTrigger> orientationStateTriggers = visualStateGroups.SelectMany(visualStateGroup => visualStateGroup.States)
                                                                                 .SelectMany(visualState => visualState.StateTriggers)
                                                                                 .Where(stateTriggerBase => stateTriggerBase is OrientationStateTrigger)
                                                                                 .Cast <OrientationStateTrigger>();
                foreach (OrientationStateTrigger orientationStateTrigger in orientationStateTriggers)
                {
                    orientationStateTrigger.Dispose();
                }
            };

            CtorAsync();
        }
Example #50
0
 public ConfigSourceSteps(IObjectContainer container, ConfigSourceContext context, MoqContext moq, ErrorContext errors, ResourceContext resources)
 {
     _container = container;
     _context   = context;
     _moq       = moq;
     _errors    = errors;
     _resources = resources;
 }