示例#1
0
        public async Task AutoswitchCamera(EngineContext engineContext)
        {
            bool autoswitch = false;
            while (true)
            {
                // Fetch camera list
                var cameras = Context.EntityManager.Entities
                    .Where(x => x.ContainsKey(CameraComponent.Key))
                    .Select(x => x.Get(CameraComponent.Key)).ToArray();

                if (engineContext.InputManager.IsKeyPressed(Keys.F8))
                {
                    autoswitch = !autoswitch;
                }

                int index = Array.IndexOf(cameras, TrackingCamera);
                if (autoswitch)
                {
                    if (index == 1)
                        index = 2;
                    else
                        index = 1;
                    TrackingCamera = (index < cameras.Length) ? cameras[index] : null;
                }

                await TaskEx.Delay((index == 1) ? 50000 : 10000);
            }
        }
        internal void Initialize(EngineContext engineContext)
        {
            this.engineContext = engineContext;

            this.DataContext = new RootViewModel(engineContext, processInfoRenderer);
            processInfoRendererScroller.ScrollToRightEnd();
        }
示例#3
0
 public static void PipelineSetup(EngineContext engineContext, string effectFilename = null)
 {
     var config = AppConfig.GetConfiguration<Config>("Script1");
     var renderingSetup = RenderingSetup.Singleton;
     var optionalFeatures = config.PipelineFeatures.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
     renderingSetup.Initialize(engineContext, effectFilename, optionalFeatures);
 }
示例#4
0
        public RootViewModel(EngineContext engineContext, ProcessInfoRenderer processInfoRenderer)
        {
            if (engineContext == null)
                throw new ArgumentNullException("engineContext");

            if (engineContext.Scheduler == null)
                throw new InvalidOperationException("The provided EngineContext must have a Scheduler.");

            timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1.0),
                IsEnabled = true,
            };
            timer.Tick += (s, e) => Increment++;
            timer.Start();

            this.processInfoRenderer = processInfoRenderer;

            EngineContext = engineContext;
            microThreadMonitoringManager = new MicroThreadMonitoringManager(EngineContext.Scheduler);

            SnapshotCommand = new AnonymousCommand(_ => TakeSnapshot());

            //PauseCommand = new AnonymousCommand(_ => EngineContext.Scheduler.PauseExecution());
            //ResumeCommand = new AnonymousCommand(_ => EngineContext.Scheduler.ResumeExecution());
            //NextFrameCommand = new AnonymousCommand(_ => EngineContext.Scheduler.NextExecutionFrame());

            SetupMicroThreadWatching();
            SetupScriptWatching();

            StartMonitoring();
        }
示例#5
0
文件: ScriptCube.cs 项目: cg123/xenko
        public static async Task GenerateSimpleCubeEffect(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;
            renderingSetup.RegisterLighting(engineContext);

#if XENKO_YEBIS
            YebisPlugin yebisPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.Glare.Enable = false;
                yebisPlugin.DepthOfField.Enable = false;
                yebisPlugin.ToneMap.AutoExposure.Enable = false;
                yebisPlugin.ToneMap.Exposure = 1.0f;
                yebisPlugin.ToneMap.Gamma = 2.2f;
            }
#endif
            var lightPrepassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin");
            var gbufferPlugin = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin");

            EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube")
                .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("AlbedoSpecularBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("AlbedoDiffuseBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("NormalVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("SpecularPowerPerMesh") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("PositionVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("BRDFDiffuseLambert") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin(new ShaderMixinSource() {
                    new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream"))}) { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin(new ShaderMixinSource() {
                    new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic"))}) { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new GBufferShaderPlugin { RenderPassPlugin = gbufferPlugin })
                .Using(new DeferredLightingShaderPlugin() { RenderPassPlugin = lightPrepassPlugin })
                .Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                ;

            EffectOld effect2 = engineContext.RenderContext.BuildEffect("SimpleSkinning")
                .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("TransformationSkinning") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("AlbedoSpecularBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("AlbedoDiffuseBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("NormalVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("SpecularPowerPerMesh") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("PositionVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("BRDFDiffuseLambert") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new BasicShaderPlugin(new ShaderMixinSource() {
                            new ShaderClassSource("AlbedoDiffuseBase"),
                            new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorTexture", TexturingKeys.DiffuseTexture.Name, "TEXCOORD")),
                            new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")),
                    }) { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                .Using(new GBufferShaderPlugin { RenderPassPlugin = gbufferPlugin })
                .Using(new DeferredLightingShaderPlugin() { RenderPassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin") })
                .Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainTargetPlugin })
                ;
        }
        public static async Task SyncSceneLoad(EngineContext engineContext)
        {
            Process.Start(new ProcessStartInfo("git", "fetch --all") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();
            Process.Start(new ProcessStartInfo("git", "pull") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();

            // Load
            LoadScene(engineContext);
        }
示例#7
0
        public static async Task Run(EngineContext engineContext)
        {
#if PARADOX_YEBIS
            YebisPlugin yebisPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.Glare.Enable = false;
                yebisPlugin.DepthOfField.Enable = false;
                yebisPlugin.ToneMap.AutoExposure.Enable = false;
                yebisPlugin.ToneMap.Exposure = 1.0f;
                yebisPlugin.ToneMap.Gamma = 2.2f;
            }
#endif

            EffectOld effect = engineContext.RenderContext.Effects.First(x => x.Name == "Multicore");
            //Effect effect = engineContext.RenderContext.BuildEffect("Multicore")
            //    .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new BasicShaderPlugin(new ShaderMixinSource()
            //                        {
            //                            "NormalVSStream",
            //                            "PositionVSStream",
            //                            new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")),
            //                            new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values!
            //                            "BRDFDiffuseLambert",
            //                            "BRDFSpecularBlinnPhong",
            //                        }) { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new BasicShaderPlugin("AlbedoFlatShading") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    .Using(new LightingShaderPlugin { RenderPassPlugin = renderingSetup.LightingPlugin })
            //    //.Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainDepthReadOnlyPlugin })
            //    ;

            //effect.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = new Light[] { new DirectionalLight { LightColor = new Color3(1.0f), LightDirection = new R32G32B32_Float(-1.0f, -1.0f, 1.0f) } } });

            var rand = new Random();
            var cubeMeshData = Enumerable.Range(0, 10).Select(x => MeshDataHelper.CreateBox(10, 10, 10, new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), 1.0f))).ToArray();

            var effectMeshGroup = new RenderPassListEnumerator();
            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            int objectSqrtCount = 31;
            int meshCount = objectSqrtCount * objectSqrtCount * objectSqrtCount;

            for (int j = 0; j < meshCount; ++j)
            {
                var effectMesh = new EffectMesh(effect, cubeMeshData[(j / 25) % 10]);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
                effectMeshGroup.AddMesh(effectMesh);

                var w2 = Matrix.Scaling(1.0f)
                            * Matrix.Translation(new Vector3(
                                (j % objectSqrtCount - objectSqrtCount / 2) * 30.0f - 30.0f,
                                (((j / objectSqrtCount) % objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f,
                                (j / (objectSqrtCount * objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f));

                effectMesh.Parameters.Set(TransformationKeys.World, w2);
            }
        }
示例#8
0
        public static async Task Run(EngineContext engineContext)
        {
            var config = AppConfig.GetConfiguration<Config>("Script1");

            CommonSetup(engineContext);

            if (config.Synthetic)
            {
                await ScriptCube.Run(engineContext);
            }
            else
            {
                PipelineSetup(engineContext);

                // Check config file
                var configDebug = AppConfig.GetConfiguration<ScriptDebug.Config>("ScriptDebug");
                if (configDebug.DebugManager)
                    engineContext.Scheduler.Add(() => ScriptDebug.RunDebug(engineContext));

                engineContext.Scheduler.Add(async () =>
                    {
                        if (config.Scene == "cave")
                        {
                            VirtualFileSystem.MountFileSystem("/sync", ".");
                            await ScriptCave.Run(engineContext);
                        }
                        else if (config.Scene == "sync")
                        {
                            ScriptSceneSerialization.gitFolder = "..\\..\\gittest\\" + config.SyncFolder + "\\";
                            VirtualFileSystem.MountFileSystem("/sync", ScriptSceneSerialization.gitFolder);
                            await ScriptCube.GenerateSimpleCubeEffect(engineContext);
                        }
                        else if (config.Scene == "factory")
                        {
                            await SetupFactory(engineContext);
                            await LightScript.MoveLights(engineContext);
                        }
                        else if (config.Scene == "particles")
                        {
                            //ScriptParticleSmoke.Run(engineContext);
                        }
                        else if (config.Scene == "cputest")
                        {
                            await ScriptMulticore.Run(engineContext);
                        }
                        else if (config.Scene == "permutation")
                        {
                            await ScriptPermutation.Run(engineContext);
                        }
                    });
            }
        }
        public static async Task SyncSceneMerge(EngineContext engineContext)
        {
            // Save
            await SaveScene(engineContext);

            Process.Start(new ProcessStartInfo("git", "add package_scene.hotei") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();
            Process.Start(new ProcessStartInfo("git", "commit -m Message") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();
            Process.Start(new ProcessStartInfo("git", "fetch --all") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();
            Process.Start(new ProcessStartInfo("git", "merge origin/master") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();
            Process.Start(new ProcessStartInfo("git", "push origin master") { WorkingDirectory = gitFolder, CreateNoWindow = true, UseShellExecute = false }).WaitForExit();

            // Load
            LoadScene(engineContext);
        }
        public ScriptManagerControl(EngineContext engineContext, Action terminateCommand)
        {
            InitializeComponent();

            if (engineContext == null)
                throw new ArgumentNullException("engineContext");

            if (terminateCommand != null)
                TerminateCommand = new AnonymousCommand(_ => terminateCommand());

            this.Loaded += (s, e) =>
            {
                scriptEditor.Initialize(engineContext);
                scriptMonitor.Initialize(engineContext);
            };

        }
示例#11
0
        public static void CommonSetup(EngineContext engineContext)
        {
            VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\");
            VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\");
            VirtualFileSystem.MountFileSystem("/shaders", "..\\..\\sources\\shaders\\");

            engineContext.EntityManager.Systems.Add(new MeshProcessor());
            engineContext.EntityManager.Systems.Add(new HierarchicalProcessor());
            engineContext.EntityManager.Systems.Add(new AnimationProcessor());
            engineContext.EntityManager.Systems.Add(new TransformationProcessor());
            engineContext.EntityManager.Systems.Add(new TransformationUpdateProcessor());
            engineContext.EntityManager.Systems.Add(new SkinningProcessor());
            engineContext.EntityManager.Systems.Add(new ModelConverterProcessor(engineContext));

            engineContext.AssetManager.RegisterSerializer(new GpuTextureSerializer(engineContext.RenderContext.GraphicsDevice));
            engineContext.AssetManager.RegisterSerializer(new GpuSamplerStateSerializer(engineContext.RenderContext.GraphicsDevice));
            engineContext.AssetManager.RegisterSerializer(new ImageSerializer());
        }
示例#12
0
文件: ScriptSync.cs 项目: cg123/xenko
        public static void SaveAssets(EngineContext engineContext)
        {
            var entities = new List<EntityDefinition>();

            foreach (var entity in engineContext.EntityManager.Entities.OrderBy(x => x.Guid).Where(x => x.Name == "him"))
            {
                var entityDefinition = new EntityDefinition(entity.Guid);
                entities.Add(entityDefinition);

                foreach (var entityComponent in entity.Properties.Where(x => x.Value is EntityComponent).OrderBy(x => x.Key.Name))
                {
                    var componentDefinition = new EntityComponentDefinition { Name = entityComponent.Key.Name, Properties = new List<EntityComponentProperty>() };
                    entityDefinition.Components.Add(componentDefinition);

                    var entityComponentValue = entityComponent.Value as EntityComponent;

                    foreach (var field in entityComponentValue.GetType().GetFields())
                    {
                        if (field.GetCustomAttributes(typeof(VersionableAttribute), true).Length == 0)
                            continue;

                        componentDefinition.Properties.Add(new EntityComponentProperty(EntityComponentPropertyType.Field, field.Name, Encode(field.GetValue(entityComponentValue))));
                    }

                    foreach (var property in entityComponentValue.GetType().GetProperties())
                    {
                        if (property.GetCustomAttributes(typeof(VersionableAttribute), true).Length == 0)
                            continue;

                        componentDefinition.Properties.Add(new EntityComponentProperty(EntityComponentPropertyType.Property, property.Name, Encode(property.GetValue(entityComponentValue, null))));
                    }

                    componentDefinition.Properties = componentDefinition.Properties.OrderBy(x => x.Name).ToList();
                }
            }

            var fileStream = new FileStream(@"C:\DEV\hotei_scene\scene.hotei", FileMode.Create, FileAccess.Write);
            var stream = new BinarySerializationWriter(fileStream);
            stream.Context.Serializer = Serializer;
            stream.SerializeClass(null, ref entities, ArchiveMode.Serialize);
            fileStream.Close();
        }
        //[XenkoScript(ScriptFlags.AssemblyStartup)]
        public static async Task SaveScene2(EngineContext engineContext)
        {
            var assetManager = new AssetManager(new AssetSerializerContextGenerator(engineContext.PackageManager));

            var entity = new Entity();
            var meshComponent = entity.GetOrCreate(ModelComponent.Key);
            meshComponent.SubMeshes.Add(new EffectMeshData { MeshData = new SubMeshData { DrawCount = 321 } });
            var entities = new[] { entity };

            throw new NotImplementedException();
            //var convertedEntities = assetManager.Convert<EntityGroup, IList<Entity>>(entities, "/data/package_scene.hotei#");
            //assetManager.Save(convertedEntities);

            //var contents = ParameterContainerExtensions.EnumerateContentData(convertedEntities).ToArray();
            //var sceneText = ParameterContainerExtensions.ConvertToText(contents[0]);
            //File.WriteAllText("current_scene.txt", sceneText);

            //ParameterContainerExtensions.ConvertFromText(engineContext, sceneText, "/data/package_scene_copy.hotei#/root");
            //var convertedEntities2 = assetManager.Load<EntityGroup>("/data/package_scene_copy.hotei#");
        }
示例#14
0
        public static async Task Run(EngineContext engineContext)
        {
            ParticlePlugin particlePlugin;
            if (!engineContext.DataContext.RenderPassPlugins.TryGetValueCast("ParticlePlugin", out particlePlugin))
                return;

            var count = particlePlugin.CapacityCount;

            var particlesBuffer = new ParticleData[count];
            var random = new Random();
            for (int i = 0; i < particlesBuffer.Length; i++)
            {
                particlesBuffer[i] = new ParticleData
                    {
                        Position = new Vector3(1000.0f - (float)random.NextDouble() * 6000, 1500.0f - (float)random.NextDouble() * 3000.0f, 0),
                        Velocity = new Vector3(0, 0, 2.0f + 10.0f * (float)random.NextDouble()),
                        Time = 5000.0f * (float)random.NextDouble(),
                        Size = 1.0f + (float)random.NextDouble() * 10.0f,
                        Factors = new Vector3(1.0f + ((i & 255) == 0 ? (25.0f + 50.0f * (float)random.NextDouble()) : -(float)random.NextDouble() * ((i & 3) == 0 ? 2.0f : 1.0f)), 0, 0),
                        Opacity = 1.0f,
                    };
                particlesBuffer[i].Position.Z = particlesBuffer[i].Velocity.Z * particlesBuffer[i].Time / 100.0f;
            }

            var particleUpdater = new ParticleEmitterComponent()
                {
                    Type = ParticleEmitterType.GpuStatic,
                    Count = count,
                    Shader = new ShaderClassSource("ParticleUpdaterTest1"),
                };
            particleUpdater.ParticleData = particlesBuffer;
            particleUpdater.ParticleElementSize = Utilities.SizeOf<ParticleData>();

            // Add this particle updater to the particle engine
            particlePlugin.Updaters.Add(particleUpdater);
        }
示例#15
0
        public static async Task MoveLights(EngineContext engineContext)
        {
            var r = new Random(0);

            var config = AppConfig.GetConfiguration<Config>("LightScript2");

            LightingPrepassPlugin lightingPrepassPlugin;
            if (!engineContext.DataContext.RenderPassPlugins.TryGetValueCast("LightingPrepassPlugin", out lightingPrepassPlugin))
                return;

            var effectMeshGroup = new RenderPassListEnumerator();
            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            // Lights
            for (int i = 0; i < 1024; ++i)
            {
                var effectMesh = new EffectMesh(lightingPrepassPlugin.Lights);

                Color3 color = (Color3)Color.White;
                switch (i % 7)
                {
                    case 0: color = new Color3(0.7f, 0.0f, 0.0f); break;
                    case 1: color = new Color3(0.0f, 0.7f, 0.0f); break;
                    case 2: color = new Color3(0.0f, 0.0f, 0.7f); break;
                    case 3: color = new Color3(0.7f, 0.7f, 0.0f); break;
                    case 4: color = new Color3(0.7f, 0.0f, 0.7f); break;
                    case 5: color = new Color3(0.0f, 0.7f, 0.7f); break;
                    case 6: color = new Color3(0.7f, 0.7f, 0.7f); break;
                }
                effectMesh.Parameters.Set(LightKeys.LightRadius, 60.0f);
                effectMesh.Parameters.Set(LightKeys.LightColor, color);
                effectMesh.Parameters.Set(LightKeys.LightIntensity, 1.0f);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);

                effectMeshGroup.AddMesh(effectMesh);
            } 
            
            bool animatedLights = config.AnimatedLights;

            EffectOld effectLight = null;
            try
            {
                effectLight = engineContext.RenderContext.RenderPassPlugins.OfType<LightingPrepassPlugin>().FirstOrDefault().Lights;
            }
            catch
            {
                return;
            }

            var lightInfo = new LightInfo[effectLight != null ? effectLight.Meshes.Count : 0];
            for (int i = 0; i < lightInfo.Length; ++i)
            {
                lightInfo[i].Radius = (float)r.NextDouble() * 1000.0f + 500.0f;
                lightInfo[i].Phase = (float)r.NextDouble() * 10.0f;
                lightInfo[i].Z = (float)r.NextDouble() * 150.0f + 150.0f;
            }
            float time = 0.0f;
            var st = new Stopwatch();
            var lastTickCount = 0;

            var st2 = new Stopwatch();
            st2.Start();

            bool firstTime = true;
            while (true)
            {
                await Scheduler.NextFrame();

                time += 0.003f;

                if (lightInfo.Length > 0)
                {
                    if (animatedLights || firstTime)
                    {
                        int index = 0;
                        foreach (var mesh in effectLight.Meshes)
                        {
                            mesh.Parameters.Set(LightKeys.LightPosition, new Vector3(lightInfo[index].Radius * (float)Math.Cos(time * 3.0f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(time * 3.0f + lightInfo[index].Phase), lightInfo[index].Z));
                            index++;
                        }

                        firstTime = false;
                    }
                }
            }
        }
示例#16
0
        public static void Run(EngineContext engineContext)
        {
            ParticlePlugin particlePlugin;
            if (!engineContext.DataContext.RenderPassPlugins.TryGetValueCast("ParticlePlugin", out particlePlugin))
                return;

            //engineContext.RenderContext.UIControl.KeyUp += (sender, args) =>
            //    {
            //        if (args.KeyCode >= Keys.F1 && args.KeyCode <= Keys.F12)
            //        {

            //            var stream = new FileStream("picking.txt", FileMode.Append);
            //            var streamWriter = new StreamWriter(stream);
            //            streamWriter.WriteLine("---------------------------------------------");
            //            streamWriter.WriteLine("- {0}", args.KeyCode);
            //            streamWriter.WriteLine("---------------------------------------------");
            //            streamWriter.Flush();
            //            stream.Close();
            //        }
            //    };

            var particleSystem = engineContext.EntityManager.GetSystem<ParticleProcessor>();

            var emitterPositions = new[]
                {
                    new Vector3(-2047.287f, -613.5108f, -400.0f),						// 0
                    new Vector3(-1881.002f, -564.9566f, -400.0f),						// 1
                    new Vector3(-1627.844f, -449.1949f, -400.0f),						// 2
                    new Vector3(-1391.335f, -423.1865f, -400.0f),						// 3
                    new Vector3(-1314.865f, -482.0599f, -400.0f),						// 4
                    new Vector3(-1019.54f, -932.4803f,  -400.0f),						// 5
                    new Vector3(-957.3735f, -988.7004f, -400.0f),						// 6
                    new Vector3(-759.9126f, -1168.646f, -400.0f),						// 7
                    new Vector3(-529.1716f, -1083.003f, -400.0f),						// 8
                    new Vector3(-198.7756f, -1029.24f,  -400.0f),						// 9
                    new Vector3(309.9702f, -832.7861f,  -400.0f),						// 10
                    new Vector3(876.9819f, -667.9489f,  -400.0f),						// 11
                    new Vector3(1908.686f, -1085.583f,  -400.0f),						// 12
                    new Vector3(2308.45f, -995.1572f,   -400.0f),						// 13
                    new Vector3(2864.581f, -906.4545f,  -400.0f),						// 14
                    new Vector3(3770.119f, -832.0695f,  -400.0f),						// 15
                    new Vector3(4561.941f, -728.9376f,  -400.0f),						// 16
                    new Vector3(5429.49f, -722.3638f,   -400.0f),						// 17
                    new Vector3(6447.015f, -310.0454f,  -400.0f),						// 18
                    new Vector3(6420.864f, 532.3475f,   -400.0f),						// 19
                    new Vector3(6157.83f, 658.0294f,    -400.0f),						// 20
                    new Vector3(4732.579f, 955.4061f,   -400.0f),						// 21
                    new Vector3(1630.28f, 1551.338f,    -400.0f),						// 22
                    new Vector3(931.7393f, 1274.533f,   -400.0f),						// 23
                    new Vector3(1586.493f, 1505.558f,   -400.0f),						// 24
                    new Vector3(906.572f, 1268.478f,    -400.0f),						// 25
                    new Vector3(390.1973f, 1314.976f,   -400.0f),						// 26
                    new Vector3(-30.39231f, 1553.894f,  -400.0f),						// 27
                    new Vector3(-356.4023f, 1605.162f,  -400.0f),						// 28
                    new Vector3(-1055.699f, 971.7286f,  -400.0f),						// 29
                    new Vector3(-1218.041f, 727.1427f,  -400.0f),						// 30
                    new Vector3(-1377.148f, 606.9602f,  -400.0f),						// 31
                    new Vector3(-1676.512f, 640.7913f,  -400.0f),						// 32
                    new Vector3(-2089.593f, 833.8343f,  -400.0f),						// 33
                    new Vector3(-2290.1f, 992.6068f,    -400.0f),						// 34
                    new Vector3(-2196.059f, 764.4152f,  -400.0f),						// 35
                    new Vector3(-1448.233f, 391.5037f,  -400.0f),						// 36
                    new Vector3(-1337.535f, 223.827f,   -400.0f),						// 37
                    new Vector3(-1287.335f, -125.6966f, -400.0f),						// 38
                    new Vector3(-4226.484f, -1213.027f, -400.0f),						// 39 - Magma Left
                    new Vector3(-4593.09f, -1091.131f,  -400.0f),						// 40
                    new Vector3(-4803.661f, -958.4816f, -400.0f),						// 41
                    new Vector3(-5262.959f, -1025.99f,  -400.0f),						// 42
                    new Vector3(-5519.119f, -881.3628f, -400.0f),						// 43
                    new Vector3(-5543.972f, -547.7667f, -400.0f),						// 44
                    new Vector3(-5775.069f, -294.6195f, -400.0f),						// 45
                    new Vector3(-6333.859f, -423.4442f, -400.0f),						// 46
                    new Vector3(-6977.528f, 840.5598f,  -400.0f),						// 47
                    new Vector3(-6847.938f, 1640.414f,  -400.0f),						// 48
                    new Vector3(-7259.18f, 1724.889f,   -400.0f),						// 49
                    new Vector3(-7693.181f, 1660.773f,  -400.0f),						// 50
                    new Vector3(-8300.401f, 1609.711f,  -400.0f),						// 51
                    new Vector3(-8704.221f, 1241.705f,  -400.0f),						// 52
                    new Vector3(-9049.8f, 905.2922f,    -400.0f),						// 53
                    new Vector3(-8739.72f, 105.7951f,   -400.0f),						// 54
                    new Vector3(-8515.267f, -371.7517f, -400.0f),						// 55
                    new Vector3(-8110.098f, -316.8557f, -400.0f),						// 56
                    new Vector3(-7915.391f, -304.8632f, -400.0f),						// 57
                    new Vector3(-7191.82f, -353.2674f,  -400.0f),						// 58
                    new Vector3(-6270.604f, -2246.958f, -400.0f),						// 59 - Magma right
                    new Vector3(-6655.961f, -2615.954f, -400.0f),						// 60
                    new Vector3(-7056.6f, -2839.48f,    -400.0f),						// 61
                    new Vector3(-7632.455f, -3047.234f, -400.0f),						// 62
                    new Vector3(-8325.431f, -2937.415f, -400.0f),						// 63
                    new Vector3(-8273.172f, -3403.743f, -400.0f),						// 64
                    new Vector3(-8179.38f, -3616.764f,  -400.0f),						// 65
                    new Vector3(-7814.024f, -4484.587f, -400.0f),						// 66
                    new Vector3(-6525.229f, -4816.507f, -400.0f),						// 67
                    new Vector3(-5648.252f, -4344.051f, -400.0f),						// 68
                    new Vector3(-6140.713f, -3957.125f, -400.0f),						// 69
                    new Vector3(-7001.114f, -3650.077f, -400.0f),						// 70
                };


            var random = new Random(1);

            var emitters = new SmokeParticleEmitterComponent[emitterPositions.Length];
            for (int i = 0; i < emitters.Length; i++)
            {

                var verticalScatter = (float)(2.0 + 3.0 * random.NextDouble());
                var horizontalScatter = (float)(3.0 + 6.0 * random.NextDouble());

                var emitter = new SmokeParticleEmitterComponent()
                    {
                        Count = 256,
                        Description = new SmokeEmitterDescription()
                        {
                            Position = emitterPositions[i],
                            Scatter = new Vector3(horizontalScatter, horizontalScatter, verticalScatter),
                            Velocity = new Vector3(0, 0.0f, 0.5f + 4.0f * (float)random.NextDouble()),
                            MaxTime = 1000.0f + 4000.0f * (float)random.NextDouble(),
                            InitialSize = 50.0f + 30.0f * (float)random.NextDouble(),
                            DeltaSize = 30.0f + 20.0f * (float)random.NextDouble(),
                            Opacity = 0.7f,
                        }
                    };
                emitter.OnUpdateData();

                emitters[i] = emitter;
            }

            var smokeVolTexture = (Texture2D)engineContext.AssetManager.Load<Texture>("/global_data/gdc_demo/fx/smokevol.dds");
            var smokeGradTexture = (Texture2D)engineContext.AssetManager.Load<Texture>("/global_data/gdc_demo/fx/smokegrad.dds");
            particlePlugin.Parameters.Set(SmokeTexture, smokeVolTexture);
            particlePlugin.Parameters.Set(SmokeColor, smokeGradTexture);

            var particleEmitterRootEntity = new Entity("ParticleEmitters");
            particleEmitterRootEntity.Set(TransformationComponent.Key, new TransformationComponent());
            engineContext.EntityManager.AddEntity(particleEmitterRootEntity);

            for (int index = 0; index < emitters.Length; index++)
            {
                var emitter = emitters[index];
                var entity = new Entity(string.Format("ParticleEmitter-{0}", index));
                entity.Set(TransformationComponent.Key, new TransformationComponent(new TransformationTRS { Translation = emitter.Description.Position }));
                entity.Set(ParticleEmitterComponent.Key, emitter);

                particleEmitterRootEntity.Transformation.Children.Add(entity.Transformation);
            }
        }
示例#17
0
        public EjTable GetTable(string tableName,
                                ViewDataDictionary viewData, HttpRequestBase Request, string SubSystemName, string ControllerName,
                                string ControllerMethod,
                                string ServiceMethodName, IDataTable debatable = null)
        {
            try
            {
                if (string.IsNullOrEmpty(tableName))
                {
                    throw new Exception("tableName is null");
                }

                tableName = tableName.ToLower().TrimEnd();


                using (var db = new EngineContext())
                {
                    var table = db.Tables.Include("TableMethods")
                                .Include("UiTableForms")
                                .Include("UiTableItems").Include("UiTableItems.UiItem")
                                .FirstOrDefault(t => t.Name.ToLower().TrimEnd() == tableName);
                    if (table == null)
                    {
                        throw new UiEngineException("جدول یافت نشد");
                    }


                    var searchForm = table.UiTableForms.FirstOrDefault();
                    if (searchForm != null)
                    {
                        _uiFormprovider.GetForm(searchForm.Name, viewData, isTableForm: true,
                                                postType: UiFormControllerMethodType.Search);
                    }



                    if (debatable == null)
                    {
                        var methodId = table.TableMethods.Select(t => t.DefineControllerMethodId).First();

                        debatable = CallServiceMethod(methodId, Request.Form, Request.Params,
                                                      out SubSystemName, out ControllerName, out ControllerMethod
                                                      , out ServiceMethodName);
                    }


                    ControllerName = ControllerName.Replace("Controller", "");

                    viewData[UiHomeController.ApiActionURL] = Request.ApplicationPath +
                                                              $@"{SubSystemName}/api/{ControllerName}/{
                                                                      ControllerMethod
                                                                  }" +
                                                              Request.Url.Query;
                    viewData[UiHomeController.ActionURL] = Request.ApplicationPath +
                                                           $@"{SubSystemName}/{ControllerName}/{ControllerMethod}" +
                                                           Request.Url.Query;
                    viewData[UiHomeController.TableObject]  = table;
                    viewData[UiHomeController.DataTable]    = debatable;
                    viewData[UiHomeController.UiTableItems] = table.UiTableItems;

                    return(table);
                }
            }
            catch (UiEngineException e)
            {
                throw e;
            }
        }
示例#18
0
        public static async Task MoveLights(EngineContext engineContext)
        {
            var r = new Random(0);

            var config = AppConfig.GetConfiguration <Config>("LightScript2");

            LightingPrepassPlugin lightingPrepassPlugin;

            if (!engineContext.DataContext.RenderPassPlugins.TryGetValueCast("LightingPrepassPlugin", out lightingPrepassPlugin))
            {
                return;
            }

            var effectMeshGroup = new RenderPassListEnumerator();

            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            // Lights
            for (int i = 0; i < 1024; ++i)
            {
                var effectMesh = new EffectMesh(lightingPrepassPlugin.Lights);

                Color3 color = (Color3)Color.White;
                switch (i % 7)
                {
                case 0: color = new Color3(0.7f, 0.0f, 0.0f); break;

                case 1: color = new Color3(0.0f, 0.7f, 0.0f); break;

                case 2: color = new Color3(0.0f, 0.0f, 0.7f); break;

                case 3: color = new Color3(0.7f, 0.7f, 0.0f); break;

                case 4: color = new Color3(0.7f, 0.0f, 0.7f); break;

                case 5: color = new Color3(0.0f, 0.7f, 0.7f); break;

                case 6: color = new Color3(0.7f, 0.7f, 0.7f); break;
                }
                effectMesh.Parameters.Set(LightKeys.LightRadius, 60.0f);
                effectMesh.Parameters.Set(LightKeys.LightColor, color);
                effectMesh.Parameters.Set(LightKeys.LightIntensity, 1.0f);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);

                effectMeshGroup.AddMesh(effectMesh);
            }

            bool animatedLights = config.AnimatedLights;

            EffectOld effectLight = null;

            try
            {
                effectLight = engineContext.RenderContext.RenderPassPlugins.OfType <LightingPrepassPlugin>().FirstOrDefault().Lights;
            }
            catch
            {
                return;
            }

            var lightInfo = new LightInfo[effectLight != null ? effectLight.Meshes.Count : 0];

            for (int i = 0; i < lightInfo.Length; ++i)
            {
                lightInfo[i].Radius = (float)r.NextDouble() * 1000.0f + 500.0f;
                lightInfo[i].Phase  = (float)r.NextDouble() * 10.0f;
                lightInfo[i].Z      = (float)r.NextDouble() * 150.0f + 150.0f;
            }
            float time          = 0.0f;
            var   st            = new Stopwatch();
            var   lastTickCount = 0;

            var st2 = new Stopwatch();

            st2.Start();

            bool firstTime = true;

            while (true)
            {
                await Scheduler.NextFrame();

                time += 0.003f;

                if (lightInfo.Length > 0)
                {
                    if (animatedLights || firstTime)
                    {
                        int index = 0;
                        foreach (var mesh in effectLight.Meshes)
                        {
                            mesh.Parameters.Set(LightKeys.LightPosition, new Vector3(lightInfo[index].Radius * (float)Math.Cos(time * 3.0f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(time * 3.0f + lightInfo[index].Phase), lightInfo[index].Z));
                            index++;
                        }

                        firstTime = false;
                    }
                }
            }
        }
        public new void SetUp()
        {
            _pictureService                = MockRepository.GenerateMock <IPictureService>();
            _authenticationService         = MockRepository.GenerateMock <IAuthenticationService>();
            _localizationService           = MockRepository.GenerateMock <ILocalizationService>();
            _workContext                   = MockRepository.GenerateMock <IWorkContext>();
            _vendorService                 = MockRepository.GenerateMock <IVendorService>();
            _productTemplateService        = MockRepository.GenerateMock <IProductTemplateService>();
            _dateRangeService              = MockRepository.GenerateMock <IDateRangeService>();
            _genericAttributeService       = MockRepository.GenerateMock <IGenericAttributeService>();
            _storeService                  = MockRepository.GenerateMock <IStoreService>();
            _productAttributeService       = MockRepository.GenerateMock <IProductAttributeService>();
            _taxCategoryService            = MockRepository.GenerateMock <ITaxCategoryService>();
            _measureService                = MockRepository.GenerateMock <IMeasureService>();
            _catalogSettings               = new CatalogSettings();
            _specificationAttributeService = MockRepository.GenerateMock <ISpecificationAttributeService>();
            _orderSettings                 = new OrderSettings();
            _categoryService               = MockRepository.GenerateMock <ICategoryService>();
            _manufacturerService           = MockRepository.GenerateMock <IManufacturerService>();
            _customerService               = MockRepository.GenerateMock <ICustomerService>();
            _newsLetterSubscriptionService = MockRepository.GenerateMock <INewsLetterSubscriptionService>();
            _productEditorSettings         = new ProductEditorSettings();
            _customerAttributeFormatter    = MockRepository.GenerateMock <ICustomerAttributeFormatter>();

            var httpContextAccessor = MockRepository.GenerateMock <IHttpContextAccessor>();
            var nopEngine           = MockRepository.GenerateMock <NopEngine>();
            var serviceProvider     = MockRepository.GenerateMock <IServiceProvider>();
            var urlRecordService    = MockRepository.GenerateMock <IUrlRecordService>();
            var picture             = new Picture
            {
                Id          = 1,
                SeoFilename = "picture"
            };

            _genericAttributeService.Expect(p => p.GetAttributesForEntity(1, "Customer"))
            .Return(new List <GenericAttribute>
            {
                new GenericAttribute
                {
                    EntityId = 1,
                    Key      = "manufacturer-advanced-mode",
                    KeyGroup = "Customer",
                    StoreId  = 0,
                    Value    = "true"
                }
            });
            _authenticationService.Expect(p => p.GetAuthenticatedCustomer()).Return(GetTestCustomer());
            _pictureService.Expect(p => p.GetPictureById(1)).Return(picture);
            _pictureService.Expect(p => p.GetThumbLocalPath(picture)).Return(@"c:\temp\picture.png");
            _pictureService.Expect(p => p.GetPicturesByProductId(1, 3)).Return(new List <Picture> {
                picture
            });
            _productTemplateService.Expect(p => p.GetAllProductTemplates()).Return(new List <ProductTemplate> {
                new ProductTemplate {
                    Id = 1
                }
            });
            _dateRangeService.Expect(d => d.GetAllDeliveryDates()).Return(new List <DeliveryDate> {
                new DeliveryDate {
                    Id = 1
                }
            });
            _dateRangeService.Expect(d => d.GetAllProductAvailabilityRanges()).Return(new List <ProductAvailabilityRange> {
                new ProductAvailabilityRange {
                    Id = 1
                }
            });
            _taxCategoryService.Expect(t => t.GetAllTaxCategories()).Return(new List <TaxCategory> {
                new TaxCategory()
            });
            _vendorService.Expect(v => v.GetAllVendors(showHidden: true)).Return(new PagedList <Vendor>(new List <Vendor> {
                new Vendor {
                    Id = 1
                }
            }, 0, 10));
            _measureService.Expect(m => m.GetAllMeasureWeights()).Return(new List <MeasureWeight> {
                new MeasureWeight()
            });
            _categoryService.Expect(c => c.GetProductCategoriesByProductId(1, true)).Return(new List <ProductCategory>());
            _manufacturerService.Expect(m => m.GetProductManufacturersByProductId(1, true)).Return(new List <ProductManufacturer>());

            nopEngine.Expect(x => x.ServiceProvider).Return(serviceProvider);
            serviceProvider.Expect(x => x.GetRequiredService(typeof(IGenericAttributeService))).Return(_genericAttributeService);
            serviceProvider.Expect(x => x.GetRequiredService(typeof(IUrlRecordService))).Return(urlRecordService);
            serviceProvider.Expect(x => x.GetRequiredService(typeof(ILocalizationService))).Return(_localizationService);
            serviceProvider.Expect(x => x.GetRequiredService(typeof(IWorkContext))).Return(_workContext);
            serviceProvider.Expect(x => x.GetRequiredService(typeof(IHttpContextAccessor))).Return(httpContextAccessor);

            EngineContext.Replace(nopEngine);
            _exportManager = new ExportManager(_categoryService, _manufacturerService, _customerService, _productAttributeService, _pictureService, _newsLetterSubscriptionService, _storeService, _workContext, _productEditorSettings, _vendorService, _productTemplateService, _dateRangeService, _taxCategoryService, _measureService, _catalogSettings, _genericAttributeService, _customerAttributeFormatter, _orderSettings, _specificationAttributeService, _localizedEntityService);
        }
示例#20
0
        /// <summary>
        /// Builds a workspace and uses filter to find specs to evaluate.
        /// </summary>
        public static bool TryBuildWorkspaceAndCollectFilesToAnalyze(
            Tracing.Logger logger,
            PathTable pathTable,
            ICommandLineConfiguration configuation,
            out Workspace workspace,
            out IPipGraph pipGraph,
            out IReadOnlyDictionary <AbsolutePath, ISourceFile> filesToAnalyze,
            out FrontEndContext context)
        {
            workspace      = null;
            pipGraph       = null;
            filesToAnalyze = null;

            var loggingContext = new LoggingContext("DScriptAnalyzer");
            var fileSystem     = new PassThroughFileSystem(pathTable);
            var engineContext  = EngineContext.CreateNew(CancellationToken.None, pathTable, fileSystem);

            context = engineContext.ToFrontEndContext(loggingContext);

            // Parse filter string into EvaluationFilter
            var evaluationFilter = EvaluationFilter.Empty;

            if (!string.IsNullOrEmpty(configuation.Filter))
            {
                if (!TryGetEvaluationFilter(logger, loggingContext, engineContext, configuation.Filter, out evaluationFilter))
                {
                    // Error has been reported already
                    return(false);
                }
            }

            // Try parsing the workspace from config and evaluation filter
            if (!TryBuildWorkspace(
                    configuation,
                    context,
                    engineContext,
                    evaluationFilter,
                    progressHandler: null,
                    workspace: out workspace,
                    frontEndHostController: out _,
                    pipGraph: out pipGraph,
                    configuration: GetDefaultConfiguration()))
            {
                return(false);
            }

            if (configuation.Engine.Phase == EnginePhases.AnalyzeWorkspace)
            {
                // Find strict subset of specs in workspace that should be analyzed
                var collectedFilesToAnalyze = CollectFilesToAnalyze(
                    workspace,
                    pathTable,
                    configuation.Startup.ConfigFile,
                    evaluationFilter);

                if (collectedFilesToAnalyze.Count == 0)
                {
                    logger.ErrorFilterHasNoMatchingSpecs(loggingContext, configuation.Filter);
                    return(false);
                }

                filesToAnalyze = collectedFilesToAnalyze;
            }
            else
            {
                filesToAnalyze = new Dictionary <AbsolutePath, ISourceFile>();
            }

            return(true);
        }
示例#21
0
 public static async Task Run2(EngineContext engineContext)
 {
     for (int i = 0; i < 10; i++)
         Scheduler.Current.Add(Run3);
 }
示例#22
0
 public static ENodeConfiguration InitLotteryEngine(this ENodeConfiguration enodeConfiguration)
 {
     EngineContext.Initialize();
     return(enodeConfiguration);
 }
示例#23
0
        protected void Application_Start()
        {
            log.Info("Start Application");

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            // disable the X-AspNetMvc-Version: header
            MvcHandler.DisableMvcResponseHeader = true;

            //initialize engine context
            EngineContext.Initialize(false);

            //set dependency resolver
            var dependencyResolver = new FalconDependencyResolver();

            DependencyResolver.SetResolver(dependencyResolver);

            //model binders
            ModelBinders.Binders.Add(typeof(BaseModel), new FalconModelBinder());

            //MvcMiniprofiler
            MiniProfiler.Settings.IgnoredPaths = new string[] { "/upload/", "/mini-profiler-", "themes", "thumbnail", "/content/", "/scripts/", "/favicon.ico", "/asset.axd" };
            MiniProfiler.Settings.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter();

            //remove all view engines
            System.Web.Mvc.ViewEngines.Engines.Clear();
            //except the themeable razor view engine we use
            //System.Web.Mvc.ViewEngines.Engines.Add(new ThemableRazorViewEngine());
            System.Web.Mvc.ViewEngines.Engines.Add(new ProfilingViewEngine());

            //Add some functionality on top of the deafult ModelMetadataProvider
            ModelMetadataProviders.Current = new FalconMetadataProvider();

            //Registering some regular mvc stuf
            var stopwatch2 = new Stopwatch();

            stopwatch2.Start();

            RegisterIgnoreRoutes(RouteTable.Routes);
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            stopwatch2.Stop();
            log.Info("Register Routes cost " + stopwatch2.Elapsed);

            GlobalFilters.Filters.Add(new ProfilingActionFilter());
            RegisterGlobalFilters(GlobalFilters.Filters);

            //For debugging
            // Read RouteDebugEnable setting in web.config file
            //string routeDebugEnable = ConfigurationManager.AppSettings["RouteDebugEnabled"];
            //if (routeDebugEnable == "true")
            //{
            //    RouteDebug.PreApplicationStart.Start();
            //}

            DataAnnotationsModelValidatorProvider
            .AddImplicitRequiredAttributeForValueTypes = false;
            //DefaultModelBinder.ResourceClassKey = "ValidateMessages";

            //ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new FalconValidatorFactory()));

            //register virtual path provider for embedded views
            //var embeddedViewResolver = EngineContext.Current.Resolve<IEmbeddedViewResolver>();
            //var embeddedProvider = new EmbeddedViewVirtualPathProvider(embeddedViewResolver.GetEmbeddedViews());
            //HostingEnvironment.RegisterVirtualPathProvider(embeddedProvider);

            MiniProfilerEF6.Initialize();

            log.Info("Start Application Completed, cost " + stopwatch.Elapsed);
        }
示例#24
0
        public async static Task ProcessClient(EngineContext engineContext, SocketContext socketContext, SocketContext socketContextAsync)
        {
            socketContext.AddPacketHandler <DownloadFileQuery>(
                async(packet) =>
            {
                var stream = await VirtualFileSystem.OpenStreamAsync(packet.Url, VirtualFileMode.Open, VirtualFileAccess.Read);
                var data   = new byte[stream.Length];
                await stream.ReadAsync(data, 0, data.Length);
                stream.Close();
                socketContext.Send(new DownloadFileAnswer {
                    StreamId = packet.StreamId, Data = data
                });
            });

            socketContext.AddPacketHandler <UploadFilePacket>(
                async(packet) =>
            {
                var stream = await VirtualFileSystem.OpenStreamAsync(packet.Url, VirtualFileMode.Create, VirtualFileAccess.Write);
                await stream.WriteAsync(packet.Data, 0, packet.Data.Length);
                stream.Close();
            });

            var viewModelGlobalContext = new ViewModelGlobalContext();

            selectedEntitiesContext = new ViewModelContext(viewModelGlobalContext);
            selectedEntitiesContext.ChildrenPropertyEnumerators.Add(new EntityComponentEnumerator(engineContext));
            selectedEntitiesContext.ChildrenPropertyEnumerators.Add(new RenderPassPluginEnumerator());
            selectedEntitiesContext.ChildrenPropertyEnumerators.Add(new ChildrenPropertyInfoEnumerator());
            //selectedEntitiesContext.ChildrenPropertyEnumerators.Add(new EffectPropertyEnumerator(engineContext));

            var renderPassHierarchyContext = new ViewModelContext(viewModelGlobalContext);

            renderPassHierarchyContext.ChildrenPropertyEnumerators.Add(new RenderPassHierarchyEnumerator());
            renderPassHierarchyContext.Root = new ViewModelNode("Root", engineContext.RenderContext.RootRenderPass).GenerateChildren(renderPassHierarchyContext);

            var renderPassPluginsContext = new ViewModelContext(viewModelGlobalContext);

            renderPassPluginsContext.ChildrenPropertyEnumerators.Add(new RenderPassPluginsEnumerator {
                SelectedRenderPassPluginContext = selectedEntitiesContext
            });
            renderPassPluginsContext.Root = new ViewModelNode("Root", new EnumerableViewModelContent <ViewModelReference>(
                                                                  () => engineContext.RenderContext.RenderPassPlugins.Select(x => new ViewModelReference(x, true))));


            var entityHierarchyEnumerator = new EntityHierarchyEnumerator(engineContext.EntityManager, selectedEntitiesContext);
            var entityHierarchyContext    = new ViewModelContext(viewModelGlobalContext);

            entityHierarchyContext.ChildrenPropertyEnumerators.Add(entityHierarchyEnumerator);
            entityHierarchyContext.ChildrenPropertyEnumerators.Add(new ChildrenPropertyInfoEnumerator());
            entityHierarchyContext.Root = new ViewModelNode("EntityHierarchyRoot", new EnumerableViewModelContent <ViewModelReference>(
                                                                () => engineContext.EntityManager.Entities
                                                                .Where(x =>
            {
                var transformationComponent = x.Transformation;
                return(transformationComponent == null || transformationComponent.Parent == null);
            })
                                                                .Select(x => new ViewModelReference(x, true))));

            entityHierarchyEnumerator.SelectedEntities.CollectionChanged += (sender, args) =>
            {
                SelectEntity(entityHierarchyEnumerator.SelectedEntities);
            };
            //entityHierarchyContext.Root.Children.Add(new ViewModelNode("SelectedItems", EnumerableViewModelContent.FromUnaryLambda<ViewModelReference, ViewModelReference>(new NullViewModelContent(),
            //    (x) => { return new[] { new ViewModelReference(pickingSystem.SelectedEntity) }; })));

            /*(value) =>
             *  {
             *      var entityModelView = value != null ? entityHierarchyContext.GetModelView(value.Guid) : null;
             *      var entity = entityModelView != null ? (Entity)entityModelView.NodeValue : null;
             *      SelectEntity(entity);
             *  })));*/
            entityHierarchyContext.Root.Children.Add(new ViewModelNode("DropEntity", new RootViewModelContent((ExecuteCommand)((viewModel2, parameter) =>
            {
                var dropParameters = (DropCommandParameters)parameter;

                var movedItem = dropParameters.Data is Guid ? entityHierarchyContext.GetModelView((Guid)dropParameters.Data) : null;
                var newParent = dropParameters.Parent is Guid ? entityHierarchyContext.GetModelView((Guid)dropParameters.Parent) : null;

                if (newParent == null || movedItem == null)
                {
                    return;
                }

                var parent = ((Entity)newParent.NodeValue).Transformation;
                if (dropParameters.TargetIndex > parent.Children.Count)
                {
                    return;
                }

                var transformationComponent = ((Entity)movedItem.NodeValue).Transformation;
                transformationComponent.Parent = null;
                parent.Children.Insert(dropParameters.TargetIndex, transformationComponent);
            }))));

            entityHierarchyContext.Root.Children.Add(new ViewModelNode("DropAsset", new RootViewModelContent((ExecuteCommand)(async(viewModel2, parameter) =>
            {
                var dropParameters = (DropCommandParameters)parameter;

                var assetUrl = (string)dropParameters.Data;

                /*var newParent = entityHierarchyContext.GetModelView((Guid)dropParameters.Parent);
                 *
                 * if (newParent == null || assetUrl == null)
                 *  return;
                 *
                 * var parent = ((Entity)newParent.NodeValue).Transformation;
                 * if (dropParameters.ItemIndex > parent.Children.Count)
                 *  return;*/

                engineContext.Scheduler.Add(async() =>
                {
                    // Load prefab entity
                    var loadedEntityPrefab = await engineContext.AssetManager.LoadAsync <Entity>(assetUrl + "#");

                    // Build another entity from prefab
                    var loadedEntity = Prefab.Inherit(loadedEntityPrefab);

                    // Add it to scene
                    engineContext.EntityManager.AddEntity(loadedEntity);

                    if (loadedEntity.ContainsKey(AnimationComponent.Key))
                    {
                        Scheduler.Current.Add(() => AnimScript.AnimateFBXModel(engineContext, loadedEntity));
                    }
                });
            }))));

            var scriptEngineContext = new ViewModelContext(viewModelGlobalContext);

            scriptEngineContext.ChildrenPropertyEnumerators.Add(new ScriptAssemblyEnumerator(engineContext));
            scriptEngineContext.ChildrenPropertyEnumerators.Add(new ChildrenPropertyInfoEnumerator());
            scriptEngineContext.Root = new ViewModelNode(new EnumerableViewModelContent <ViewModelReference>(
                                                             () => engineContext.ScriptManager.ScriptAssemblies.Select(x => new ViewModelReference(x, true))));
            scriptEngineContext.Root.Children.Add(new ViewModelNode("RunScript", new RootViewModelContent((ExecuteCommand)(async(viewModel2, parameter) =>
            {
                var scriptName = (string)parameter;
                var matchingScript = engineContext.ScriptManager.Scripts.Where(x => x.TypeName + "." + x.MethodName == scriptName);
                if (matchingScript.Any())
                {
                    var scriptEntry = matchingScript.Single();
                    var microThread = engineContext.ScriptManager.RunScript(scriptEntry, null);
                }
            }))));

            var runningScriptsContext = new ViewModelContext(viewModelGlobalContext);

            runningScriptsContext.ChildrenPropertyEnumerators.Add(new MicroThreadEnumerator(selectedEntitiesContext));
            runningScriptsContext.ChildrenPropertyEnumerators.Add(new ChildrenPropertyInfoEnumerator());
            runningScriptsContext.Root = new ViewModelNode("MicroThreads", new EnumerableViewModelContent <ViewModelReference>(
                                                               () => engineContext.Scheduler.MicroThreads.Select(x => new ViewModelReference(x, true))
                                                               ));

            var effectsContext = new ViewModelContext(viewModelGlobalContext);

            effectsContext.ChildrenPropertyEnumerators.Add(new EffectEnumerator(selectedEntitiesContext));
            effectsContext.ChildrenPropertyEnumerators.Add(new ChildrenPropertyInfoEnumerator());
            effectsContext.Root = new ViewModelNode("Effects", new EnumerableViewModelContent <ViewModelReference>(
                                                        () => engineContext.RenderContext.Effects.Select(x => new ViewModelReference(x, true))
                                                        ));
            //effectsContext.Root.Children.Add(new ViewModelNode("PluginDefinitions", new RootViewModelContent()));

            var assetBrowserContext = new ViewModelContext(viewModelGlobalContext);

            assetBrowserContext.ChildrenPropertyEnumerators.Add(new AssetBrowserEnumerator(engineContext));
            assetBrowserContext.ChildrenPropertyEnumerators.Add(new ChildrenPropertyInfoEnumerator());
            assetBrowserContext.Root = new ViewModelNode("Root", "Root").GenerateChildren(assetBrowserContext);

            var editorContext = new ViewModelContext(viewModelGlobalContext);

            editorContext.Root = new ViewModelNode("Root");
            editorContext.Root.Children.Add(new ViewModelNode("SwitchSelectionMode", new CommandViewModelContent((sender, parameters) => { pickingSystem.ActiveGizmoActionMode = PickingSystem.GizmoAction.None; })));
            editorContext.Root.Children.Add(new ViewModelNode("SwitchTranslationMode", new CommandViewModelContent((sender, parameters) => { pickingSystem.ActiveGizmoActionMode = PickingSystem.GizmoAction.Translation; })));
            editorContext.Root.Children.Add(new ViewModelNode("SwitchRotationMode", new CommandViewModelContent((sender, parameters) => { pickingSystem.ActiveGizmoActionMode = PickingSystem.GizmoAction.Rotation; })));

            var contexts = new Dictionary <string, Tuple <ViewModelContext, ViewModelState> >();

            contexts.Add("Editor", Tuple.Create(editorContext, new ViewModelState()));
            contexts.Add("RenderPassPlugins", Tuple.Create(renderPassPluginsContext, new ViewModelState()));
            contexts.Add("RenderPasses", Tuple.Create(renderPassHierarchyContext, new ViewModelState()));
            contexts.Add("SelectedEntities", Tuple.Create(selectedEntitiesContext, new ViewModelState()));
            contexts.Add("EntityHierarchy", Tuple.Create(entityHierarchyContext, new ViewModelState()));
            contexts.Add("ScriptEngine", Tuple.Create(scriptEngineContext, new ViewModelState()));
            contexts.Add("MicroThreads", Tuple.Create(runningScriptsContext, new ViewModelState()));
            contexts.Add("AssetBrowser", Tuple.Create(assetBrowserContext, new ViewModelState()));
            contexts.Add("Effects", Tuple.Create(effectsContext, new ViewModelState()));

            int lastAckPacket = 0;

            var entitiesChangePackets = new ConcurrentQueue <EntitiesChangePacket>();

            socketContext.AddPacketHandler <EntitiesChangePacket>(
                (packet) =>
            {
                entitiesChangePackets.Enqueue(packet);
                entitiesChangePacketEvent.Set();
            });

            Action asyncThreadStart = () =>
            {
                while (true)
                {
                    Thread.Sleep(100);
                    foreach (var context in contexts)
                    {
                        // Process async data
                        Guid[] path  = null;
                        object value = null;
                        lock (context.Value.Item1)
                        {
                            var pendingNode = context.Value.Item1.GetNextPendingAsyncNode();
                            if (pendingNode != null)
                            {
                                value = pendingNode.Value;
                                path  = ViewModelController.BuildPath(pendingNode);
                            }
                        }
                        if (path != null)
                        {
                            // Temporary encoding through our serializer (until our serializer are used for packets)
                            var memoryStream = new MemoryStream();
                            var writer       = new BinarySerializationWriter(memoryStream);
                            writer.SerializeExtended(null, value, ArchiveMode.Serialize);

                            var change = new NetworkChange {
                                Path = path.ToArray(), Type = NetworkChangeType.ValueUpdateAsync, Value = memoryStream.ToArray()
                            };
                            var packet = new EntitiesChangePacket {
                                GroupKey = context.Key, Changes = new NetworkChange[] { change }
                            };
                            socketContextAsync.Send(packet);
                            break;
                        }
                    }
                }
            };

            new Thread(new ThreadStart(asyncThreadStart)).Start();

            // TODO: Move some of this code directly inside ViewModelContext/Controller classes
            while (true)
            {
                await TaskEx.WhenAny(TaskEx.Delay(250), entitiesChangePacketEvent.WaitAsync());

                EntitiesChangePacket packet;
                while (entitiesChangePackets.TryDequeue(out packet))
                {
                    ViewModelController.NetworkApplyChanges(contexts[packet.GroupKey].Item1, packet.Changes);
                    lastAckPacket = packet.Index;
                }

                // Wait a single frame so that network updates get applied properly by all rendering systems for next update
                await Scheduler.Current.NextFrame();

                // If entity disappeared, try to replace it with new one (happen during file reload)
                // It's little bit cumbersome to test, need some simplification of this specific entity view model root.
                if (selectedEntitiesContext.Root != null &&
                    selectedEntitiesContext.Root.Parent != null &&
                    selectedEntitiesContext.Root.Parent.NodeValue is Entity)
                {
                    var entity = (Entity)selectedEntitiesContext.Root.Parent.NodeValue;
                    if (!engineContext.EntityManager.Entities.Contains(entity))
                    {
                        entity = engineContext.EntityManager.Entities.FirstOrDefault(x => x.Guid == entity.Guid);
                        if (entity != null)
                        {
                            selectedEntitiesContext.ViewModelByGuid.Clear();
                            selectedEntitiesContext.Root = selectedEntitiesContext.GetModelView(entity).Children.First(x => x.PropertyName == "Components");
                        }
                    }
                }

                var data = new Dictionary <string, byte[]>();
                foreach (var context in contexts)
                {
                    lock (context.Value.Item1)
                    {
                        if (context.Value.Item1.Root != null)
                        {
                            context.Value.Item1.AddModelView(context.Value.Item1.Root);
                        }
                        ViewModelController.UpdateReferences(context.Value.Item1, true);
                        data[context.Key] = ViewModelController.NetworkSerialize(context.Value.Item1, context.Value.Item2);
                    }
                }

                viewModelGlobalContext.UpdateObjects(contexts.Select(x => x.Value.Item1));

                //Console.WriteLine("DataSize: {0}", data.Sum(x => x.Value.Length));
                await Task.Factory.StartNew(() => socketContext.Send(new EntitiesUpdatePacket {
                    AckIndex = lastAckPacket, Data = data
                }));
            }
        }
示例#25
0
        public static async Task RunDebug(EngineContext engineContext)
        {
            var config         = AppConfig.GetConfiguration <Config>("ScriptDebug");
            var renderingSetup = RenderingSetup.Singleton;

            engineContext.RenderContext.PrepareEffectPlugins += (effectBuilder, plugins) =>
            {
                if (effectBuilder.PickingPassMainPlugin != null)
                {
                    RenderPassPlugin pickingPlugin;
                    if (engineContext.DataContext.RenderPassPlugins.TryGetValue(effectBuilder.Name == "Gizmo" ? "MouseOverPickingPlugin" : "PickingPlugin", out pickingPlugin))
                    {
                        plugins.Add(new PickingShaderPlugin {
                            RenderPassPlugin = (PickingPlugin)pickingPlugin, MainPlugin = effectBuilder.PickingPassMainPlugin
                        });
                    }
                }
                if (effectBuilder.SupportWireframe)
                {
                    RenderPassPlugin wireframePlugin;
                    if (engineContext.DataContext.RenderPassPlugins.TryGetValue("WireframePlugin", out wireframePlugin))
                    {
                        plugins.Add(new WireframeShaderPlugin {
                            RenderPassPlugin = wireframePlugin, MainTargetPlugin = renderingSetup.MainTargetPlugin
                        });
                    }
                }
            };

            pickingSystem = new PickingSystem();
            pickingSystem.PropertyChanged += pickingSystem_PropertyChanged;
            engineContext.Scheduler.Add(() => pickingSystem.ProcessGizmoAndPicking(engineContext));

            var socketContext      = new SocketContext();
            var socketContextAsync = new SocketContext();

            var currentScheduler = Scheduler.Current;

            var pendingClient = new PendingClient();

            socketContext.Connected = (clientSocketContext) =>
            {
                lock (pendingClient)
                {
                    pendingClient.MainSocket = clientSocketContext;
                    if (pendingClient.AsyncSocket != null)
                    {
                        currentScheduler.Add(() => ProcessClient(engineContext, pendingClient.MainSocket, pendingClient.AsyncSocket));
                    }
                }
            };
            socketContextAsync.Connected = (clientSocketContext) =>
            {
                lock (pendingClient)
                {
                    pendingClient.AsyncSocket = clientSocketContext;
                    if (pendingClient.MainSocket != null)
                    {
                        currentScheduler.Add(() => ProcessClient(engineContext, pendingClient.MainSocket, pendingClient.AsyncSocket));
                    }
                }
            };

            socketContext.StartServer(config.Port);
            socketContextAsync.StartServer(config.Port + 1);
        }
示例#26
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     return(EngineContext.Initialize(services, ScopeTag.Http));       //用于 Api
 }
示例#27
0
        private static bool TryGetEvaluationFilter(Tracing.Logger logger, LoggingContext loggingContext, EngineContext engineContext, string filter, out EvaluationFilter evaluationFilter)
        {
            FilterParser parser = new FilterParser(
                engineContext,
                DummyPathResolver,
                filter);
            RootFilter        rootFilter;
            FilterParserError error;

            if (!parser.TryParse(out rootFilter, out error))
            {
                logger.ErrorParsingFilter(loggingContext, filter, error.Position, error.Message, error.FormatFilterPointingToPosition(filter));
                evaluationFilter = null;
                return(false);
            }

            evaluationFilter = rootFilter.GetEvaluationFilter(engineContext.SymbolTable, engineContext.PathTable);
            return(true);
        }
示例#28
0
        public static async Task SetupFactory(EngineContext engineContext, string effectName = "Simple")
        {
            var renderingSetup = RenderingSetup.Singleton;

            renderingSetup.RegisterLighting(engineContext);

            // Setup lighting
            LightingPlugin lightingPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("LightingPlugin", out lightingPlugin))
            {
                var shadowMapEntity = new Entity();
                shadowMapEntity.Set(TransformationComponent.Key, TransformationTRS.CreateComponent());
                shadowMapEntity.Set(LightComponent.Key, new LightComponent { Type = LightType.Directional, Intensity = 0.9f, Color = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(-1.0f, -1.0f, -1.0f), ShadowMap = true, DecayStart = 40000.0f });
                engineContext.EntityManager.AddEntity(shadowMapEntity);
            }

            // Load asset
            var entity = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/factoryfbx.hotei#");

            // Flip it and scale it
            var transformationComponent = (TransformationTRS)entity.Transformation.Value;
            transformationComponent.Scaling *= 0.1f;

            //await engineContext.EntitySystem.Prepare(entity);
            await engineContext.EntityManager.AddEntityAsync(entity);
        }
示例#29
0
        public static async Task SetupPostEffects(EngineContext engineContext)
        {
            var config = AppConfig.GetConfiguration<Config>("Script1");

            var renderingSetup = RenderingSetup.Singleton;
            renderingSetup.Initialize(engineContext);

            bool bloom = config.Bloom;
            bool fxaa = config.FXAA;

            bool useHBAO = false;
            bool doBlur = true;
            bool mixAOWithColorImage = false;
            bool halfResAO = true;

            var effectMeshGroup = new RenderPassListEnumerator();
            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            PostEffectPlugin postEffectPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("PostEffectPlugin", out postEffectPlugin)
                && (bloom || fxaa || useHBAO))
            {
                if (bloom)
                {
                    // Create various effects required by the bloom effect
                    EffectOld brightPassFilter = engineContext.RenderContext.BuildEffect("BrightPass")
                        .Using(new PostEffectShaderPlugin() { RenderPassPlugin = postEffectPlugin })
                        .Using(new BasicShaderPlugin("ShadingTexturing"))
                        .Using(new BasicShaderPlugin("PostEffectBrightFilter"));

                    EffectOld blurEffect = engineContext.RenderContext.BuildEffect("Blur")
                        .Using(new PostEffectShaderPlugin() { RenderPassPlugin = postEffectPlugin })
                        .Using(new BasicShaderPlugin("PostEffectBlur"));

                    EffectOld downsampleEffect = engineContext.RenderContext.BuildEffect("DownSample")
                        .Using(new PostEffectShaderPlugin() { RenderPassPlugin = postEffectPlugin })
                        .Using(new BasicShaderPlugin("ShadingTexturing"));

                    EffectOld mixEffect = engineContext.RenderContext.BuildEffect("Mix")
                        .Using(new PostEffectShaderPlugin() { RenderPassPlugin = postEffectPlugin })
                        .Using(new BasicShaderPlugin("ShadingTexturing"))
                        .Using(new BasicShaderPlugin("PosteffectTexturing2"));

                    EffectOld fxaaEffect = engineContext.RenderContext.BuildEffect("Fxaa")
                        .Using(new PostEffectShaderPlugin() { RenderPassPlugin = postEffectPlugin })
                        .Using(new BasicShaderPlugin("PostEffectFXAA.xksl"));


                    // Create post effect meshes: downsampling and blurs
                    int bloomLevels = 6;
                    var downsampleMeshes = new EffectMesh[bloomLevels];
                    var lastBlurs = new EffectMesh[bloomLevels];
                    for (int i = 0; i < bloomLevels; ++i)
                    {
                        downsampleMeshes[i] = new EffectMesh(i == 0 ? brightPassFilter : downsampleEffect, name: "Downsample " + i);
                        postEffectPlugin.AddEffectMesh(downsampleMeshes[i]);

                        // Blur effect
                        var blurQuadMesh = new EffectMesh[2];
                        for (int j = 0; j < 2; ++j)
                        {
                            blurQuadMesh[j] = new EffectMesh(blurEffect, name: string.Format("Blur level {0}:{1}", i, j));
                            blurQuadMesh[j].Parameters.Set(PostEffectBlurKeys.Coefficients, new[] { 0.30f, 0.20f, 0.20f, 0.15f, 0.15f });
                            var unit = j == 0 ? Vector2.UnitX : Vector2.UnitY;
                            blurQuadMesh[j].Parameters.Set(PostEffectBlurKeys.Offsets, new[] { Vector2.Zero, unit * -1.3862832f, unit * +1.3862832f, unit * -3.2534592f, unit * +3.2534592f });
                            postEffectPlugin.AddEffectMesh(blurQuadMesh[j]);
                        }
                        lastBlurs[i] = blurQuadMesh[1];
                        postEffectPlugin.AddLink(downsampleMeshes[i], RenderTargetKeys.RenderTarget, blurQuadMesh[0], TexturingKeys.Texture0, new TextureDescription { Width = 1024 >> (i + 1), Height = 768 >> (i + 1), Format = PixelFormat.R8G8B8A8_UNorm });
                        postEffectPlugin.AddLink(blurQuadMesh[0], RenderTargetKeys.RenderTarget, blurQuadMesh[1], TexturingKeys.Texture0);
                        if (i > 0)
                            postEffectPlugin.AddLink(downsampleMeshes[i - 1], RenderTargetKeys.RenderTarget, downsampleMeshes[i], TexturingKeys.Texture0);
                    }

                    // Create post effect meshes: mix
                    EffectMesh lastMix = null;
                    for (int i = 0; i < bloomLevels; ++i)
                    {
                        var mixMesh = new EffectMesh(mixEffect, name: "Mix " + (bloomLevels - 1 - i));
                        mixMesh.Parameters.Set(PostEffectKeys.MixCoefficients, (i < bloomLevels - 1) ? new[] { 0.10f, 0.90f } : new[] { 1.0f, 3.0f });
                        postEffectPlugin.AddEffectMesh(mixMesh);


                        if (i < bloomLevels - 1)
                            postEffectPlugin.AddLink(lastBlurs[bloomLevels - 2 - i], RenderTargetKeys.RenderTarget, mixMesh, TexturingKeys.Texture0);
                        postEffectPlugin.AddLink(lastMix ?? lastBlurs[bloomLevels - 1], RenderTargetKeys.RenderTarget, mixMesh, TexturingKeys.Texture2);

                        lastMix = mixMesh;
                    }

                    EffectMesh lastEffectMesh = lastMix;

                    //add fxaa?
                    if (fxaa)
                    {
                        var fxaaQuadMesh = new EffectMesh(fxaaEffect, name: "FXAA level");
                        postEffectPlugin.AddEffectMesh(fxaaQuadMesh);
                        postEffectPlugin.AddLink(lastMix, RenderTargetKeys.RenderTarget, fxaaQuadMesh, TexturingKeys.Texture0, new TextureDescription { Width = 1024, Height = 768, Format = PixelFormat.R8G8B8A8_UNorm });
                        lastEffectMesh = fxaaQuadMesh;
                    }

                    engineContext.RenderContext.GraphicsResizeContext.SetupResize((resizeContext) =>
                        {
                            var renderTarget = renderingSetup.MainTargetPlugin.RenderTarget;
                            //blurQuadMesh[0].Parameters.Set(TextureFeature.Texture0, renderTarget);
                            //blurQuadMesh[1].Parameters.Set(RenderTargetKeys.RenderTarget, renderTarget);
                            downsampleMeshes[0].Parameters.SetWithResize(resizeContext, TexturingKeys.Texture0, (Texture2D)renderTarget.Texture);
                            lastMix.Parameters.SetWithResize(resizeContext, TexturingKeys.Texture0, (Texture2D)renderTarget.Texture);
                            lastMix.Parameters.SetWithResize(resizeContext, RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);

                            lastEffectMesh.Parameters.SetWithResize(resizeContext, RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);
                        });
                }
                else if (fxaa)
                {
                    //fxaa effect setup (fxaa only, no bloom effect)
                    EffectOld fxaaEffect = engineContext.RenderContext.BuildEffect("Fxaa")
                        .Using(new PostEffectShaderPlugin() { RenderPassPlugin = postEffectPlugin })
                        .Using(new BasicShaderPlugin("..\\..\\sources\\shaders\\posteffect_fxaa.xksl"));

                    var fxaaQuadMesh = new EffectMesh(fxaaEffect, name: "FXAA level");

                    fxaaQuadMesh.Parameters.Set(TexturingKeys.Texture0, (Texture2D)renderingSetup.MainTargetPlugin.RenderTarget.Texture);
                    fxaaQuadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, engineContext.RenderContext.RenderTarget);
                    //fxaaQuadMesh.Parameters.Set(PostEffectFXAAKeys.FxaaQualitySubpix, 0);

                    postEffectPlugin.AddEffectMesh(fxaaQuadMesh);

                    //TODO, application will crashes if we resize or move the window!!
                }

                foreach (var mesh in postEffectPlugin.Meshes)
                    effectMeshGroup.AddMesh(mesh);

                //engineContext.RenderContext.RootRenderPass.AddPass(postEffectPlugin.RenderPass);

                engineContext.RenderContext.GraphicsResizeContext.SetupResize((resizeContext) =>
                    {
                        // Link post effects (this will create intermediate surfaces)
                        postEffectPlugin.Resolve();
                    });
            }
        }
示例#30
0
 public HomeController(EngineContext context)
 {
     db = context;
 }
        static void LoadAllPlugins()
        {
            var result = EngineContext.Resolve <PluginProcessor>().LoadAllPlugins();

            Console.WriteLine(result);
        }
示例#32
0
 public ModelConverterProcessor(EngineContext engineContext)
     : base(new PropertyKey[] { ModelConverterComponent.Key })
 {
     this.engineContext = engineContext;
 }
示例#33
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;
            //engineContext.RenderContext.Register(renderingSetup.LightingPlugin);
            //renderingSetup.RegisterLighting(engineContext);

            var shadowMapPlugin = new LightingPlugin {
                MainPlugin = renderingSetup.MainPlugin, RenderPass = engineContext.DataContext.RenderPasses.TryGetValue("ShadowMapPass")
            };

            shadowMapPlugin.RenderContext = engineContext.RenderContext;

            var shadowMap1 = new ShadowMap(new DirectionalLight())
            {
                Level = CascadeShadowMapLevel.X1, ShadowMapSize = 1024, ShadowDistance = 2000.0f
            }
            .SetFilter(sm => new ShadowMapFilterDefault(sm));
            var shadowMap2 = new ShadowMap(new DirectionalLight())
            {
                Level = CascadeShadowMapLevel.X2, ShadowMapSize = 1024, ShadowDistance = 2000.0f
            }
            .SetFilter(sm => new ShadowMapFilterVsm(sm));

            shadowMapPlugin.AddShadowMap(shadowMap1);
            shadowMapPlugin.AddShadowMap(shadowMap2);

            shadowMap1.DirectionalLight.LightDirection = new Vector3(-1.0f, -1.0f, -1.0f);
            shadowMap1.DirectionalLight.LightColor     = new Color3(1.0f, 0.5f, 0.5f);
            shadowMap2.DirectionalLight.LightDirection = new Vector3(-1.0f, 1.0f, -1.0f);
            shadowMap2.DirectionalLight.LightColor     = new Color3(0.5f, 0.5f, 1.0f);

            engineContext.RenderContext.Register(shadowMapPlugin);

            EffectOld effect = engineContext.RenderContext.BuildEffect("Permutation")
                               .Using(new BasicShaderPlugin("ShaderBase")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new BasicShaderPlugin(new ShaderMixinSource()
            {
                "NormalVSStream",
                "PositionVSStream",
                new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")),
                new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")),                         // TODO: Default values!
                "BRDFDiffuseLambert",
                "BRDFSpecularBlinnPhong",
                "ShadingBase",
            })
            {
                RenderPassPlugin = renderingSetup.MainTargetPlugin
            })
                               .Using(new LightingShaderPlugin()
            {
                RenderPassPlugin = shadowMapPlugin
            })
            ;

            var sphereMeshData = MeshDataHelper.CreateSphere(10.0f, 20, 20, Color.White);

            var effectMeshGroup = new RenderPassListEnumerator();

            engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup);

            int objectSqrtCount = 1;
            int meshCount       = objectSqrtCount * objectSqrtCount * objectSqrtCount;

            var shadowMapPermutation1 = new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap1 }
            };
            var shadowMapPermutation2 = new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap2 }
            };
            var shadowMapPermutation3 = new ShadowMapPermutationArray {
                ShadowMaps = { shadowMap1, shadowMap2 }
            };

            effect.Permutations.Set(ShadowMapPermutationArray.Key, shadowMapPermutation1);

            var groups2     = new[] { shadowMapPermutation1, shadowMapPermutation2, shadowMapPermutation3 };
            int groupIndex2 = 0;

            var effectMeshes = new List <EffectMesh>();

            for (int j = 0; j < meshCount; ++j)
            {
                var effectMesh = new EffectMesh(effect, sphereMeshData);
                effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);

                effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[2]);

                var w2 = Matrix.Scaling(1.0f)
                         * Matrix.Translation(new Vector3(
                                                  (j % objectSqrtCount - objectSqrtCount / 2) * 30.0f - 30.0f,
                                                  (((j / objectSqrtCount) % objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f,
                                                  (j / (objectSqrtCount * objectSqrtCount)) * 30.0f + 30.0f));

                effectMesh.Parameters.Set(TransformationKeys.World, w2);
                effectMeshes.Add(effectMesh);
            }

            var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(1000, 1000, 1, Color.White));

            groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry);
            effectMeshGroup.AddMesh(groundMesh);
            groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(0.0f, 0.0f, 0.0f));

            var groups     = new[] { new int[] { 0, 1 }, new int[] { 0 }, new int[] { 1 } };
            int groupIndex = 0;

            await TaskEx.Delay(1000);

            foreach (var effectMesh in effectMeshes)
            {
                effectMeshGroup.AddMesh(effectMesh);
            }

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                if (engineContext.InputManager.IsKeyPressed(Keys.F8))
                {
                    var permutation = new LightingPermutation {
                        LightBindings = { new Light() }
                    };
                    effect.Permutations.Set(LightingPermutation.Key, permutation);
                }
                if (engineContext.InputManager.IsKeyPressed(Keys.F9))
                {
                    effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[(groupIndex2++) % groups2.Length]);
                }
            }
        }
示例#34
0
 public LogFoneticaRepository(EngineContext context) : base(context)
 {
     Db    = context;
     Dbset = Db.Set <TbLogFonetica>();
 }
示例#35
0
        static BaseNopTest()
        {
            TypeDescriptor.AddAttributes(typeof(List <int>),
                                         new TypeConverterAttribute(typeof(GenericListTypeConverter <int>)));
            TypeDescriptor.AddAttributes(typeof(List <string>),
                                         new TypeConverterAttribute(typeof(GenericListTypeConverter <string>)));

            var services = new ServiceCollection();

            services.AddHttpClient();

            var memoryCache = new MemoryCache(new MemoryCacheOptions());
            var typeFinder  = new AppDomainTypeFinder();

            Singleton <DataSettings> .Instance = new DataSettings
            {
                ConnectionString = "Data Source=nopCommerceTest.sqlite;Mode=Memory;Cache=Shared"
            };

            var mAssemblies = typeFinder.FindClassesOfType <AutoReversingMigration>()
                              .Select(t => t.Assembly)
                              .Distinct()
                              .ToArray();

            //add configuration parameters
            var appSettings = new AppSettings();

            services.AddSingleton(appSettings);
            Singleton <AppSettings> .Instance = appSettings;

            var hostApplicationLifetime = new Mock <IHostApplicationLifetime>();

            services.AddSingleton(hostApplicationLifetime.Object);

            var rootPath =
                new DirectoryInfo(
                    $@"{Directory.GetCurrentDirectory().Split("bin")[0]}{Path.Combine(@"\..\..\Presentation\Nop.Web".Split('\\', '/').ToArray())}")
                .FullName;

            //Presentation\Nop.Web\wwwroot
            var webHostEnvironment = new Mock <IWebHostEnvironment>();

            webHostEnvironment.Setup(p => p.WebRootPath).Returns(Path.Combine(rootPath, "wwwroot"));
            webHostEnvironment.Setup(p => p.ContentRootPath).Returns(rootPath);
            webHostEnvironment.Setup(p => p.EnvironmentName).Returns("test");
            webHostEnvironment.Setup(p => p.ApplicationName).Returns("nopCommerce");
            services.AddSingleton(webHostEnvironment.Object);

            var httpContext = new DefaultHttpContext
            {
                Request = { Headers = { { HeaderNames.Host, NopTestsDefaults.HostIpAddress } } }
            };

            var httpContextAccessor = new Mock <IHttpContextAccessor>();

            httpContextAccessor.Setup(p => p.HttpContext).Returns(httpContext);

            services.AddSingleton(httpContextAccessor.Object);

            var actionContextAccessor = new Mock <IActionContextAccessor>();

            actionContextAccessor.Setup(x => x.ActionContext)
            .Returns(new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor()));

            services.AddSingleton(actionContextAccessor.Object);

            var urlHelperFactory = new Mock <IUrlHelperFactory>();
            var urlHelper        = new NopTestUrlHelper(actionContextAccessor.Object.ActionContext);

            urlHelperFactory.Setup(x => x.GetUrlHelper(It.IsAny <ActionContext>()))
            .Returns(urlHelper);

            services.AddTransient(provider => actionContextAccessor.Object);

            services.AddSingleton(urlHelperFactory.Object);

            var tempDataDictionaryFactory = new Mock <ITempDataDictionaryFactory>();
            var dataDictionary            = new TempDataDictionary(httpContextAccessor.Object.HttpContext,
                                                                   new Mock <ITempDataProvider>().Object);

            tempDataDictionaryFactory.Setup(f => f.GetTempData(It.IsAny <HttpContext>())).Returns(dataDictionary);
            services.AddSingleton(tempDataDictionaryFactory.Object);

            services.AddSingleton <ITypeFinder>(typeFinder);

            //file provider
            services.AddTransient <INopFileProvider, NopFileProvider>();

            //web helper
            services.AddTransient <IWebHelper, WebHelper>();

            //user agent helper
            services.AddTransient <IUserAgentHelper, UserAgentHelper>();

            //data layer
            services.AddTransient <IDataProviderManager, TestDataProviderManager>();
            services.AddTransient <INopDataProvider, SqLiteNopDataProvider>();

            //repositories
            services.AddTransient(typeof(IRepository <>), typeof(EntityRepository <>));

            //plugins
            services.AddTransient <IPluginService, PluginService>();

            services.AddSingleton <IMemoryCache>(memoryCache);
            services.AddSingleton <IStaticCacheManager, MemoryCacheManager>();
            services.AddSingleton <ILocker, MemoryCacheManager>();

            //services
            services.AddTransient <IBackInStockSubscriptionService, BackInStockSubscriptionService>();
            services.AddTransient <ICategoryService, CategoryService>();
            services.AddTransient <ICompareProductsService, CompareProductsService>();
            services.AddTransient <IRecentlyViewedProductsService, RecentlyViewedProductsService>();
            services.AddTransient <IManufacturerService, ManufacturerService>();
            services.AddTransient <IPriceFormatter, PriceFormatter>();
            services.AddTransient <IProductAttributeFormatter, ProductAttributeFormatter>();
            services.AddTransient <IProductAttributeParser, ProductAttributeParser>();
            services.AddTransient <IProductAttributeService, ProductAttributeService>();
            services.AddTransient <IProductService, ProductService>();
            services.AddTransient <ICopyProductService, CopyProductService>();
            services.AddTransient <ISpecificationAttributeService, SpecificationAttributeService>();
            services.AddTransient <IProductTemplateService, ProductTemplateService>();
            services.AddTransient <ICategoryTemplateService, CategoryTemplateService>();
            services.AddTransient <IManufacturerTemplateService, ManufacturerTemplateService>();
            services.AddTransient <ITopicTemplateService, TopicTemplateService>();
            services.AddTransient <IProductTagService, ProductTagService>();
            services.AddTransient <IAddressAttributeFormatter, AddressAttributeFormatter>();
            services.AddTransient <IAddressAttributeParser, AddressAttributeParser>();
            services.AddTransient <IAddressAttributeService, AddressAttributeService>();
            services.AddTransient <IAddressService, AddressService>();
            services.AddTransient <IAffiliateService, AffiliateService>();
            services.AddTransient <IVendorService, VendorService>();
            services.AddTransient <IVendorAttributeFormatter, VendorAttributeFormatter>();
            services.AddTransient <IVendorAttributeParser, VendorAttributeParser>();
            services.AddTransient <IVendorAttributeService, VendorAttributeService>();
            services.AddTransient <ISearchTermService, SearchTermService>();
            services.AddTransient <IGenericAttributeService, GenericAttributeService>();
            services.AddTransient <IMaintenanceService, MaintenanceService>();
            services.AddTransient <ICustomerAttributeFormatter, CustomerAttributeFormatter>();
            services.AddTransient <ICustomerAttributeParser, CustomerAttributeParser>();
            services.AddTransient <ICustomerAttributeService, CustomerAttributeService>();
            services.AddTransient <ICustomerService, CustomerService>();
            services.AddTransient <ICustomerRegistrationService, CustomerRegistrationService>();
            services.AddTransient <ICustomerReportService, CustomerReportService>();
            services.AddTransient <IPermissionService, PermissionService>();
            services.AddTransient <IAclService, AclService>();
            services.AddTransient <IPriceCalculationService, PriceCalculationService>();
            services.AddTransient <IGeoLookupService, GeoLookupService>();
            services.AddTransient <ICountryService, CountryService>();
            services.AddTransient <ICurrencyService, CurrencyService>();
            services.AddTransient <IMeasureService, MeasureService>();
            services.AddTransient <IStateProvinceService, StateProvinceService>();
            services.AddTransient <IStoreService, StoreService>();
            services.AddTransient <IStoreMappingService, StoreMappingService>();
            services.AddTransient <IDiscountService, DiscountService>();
            services.AddTransient <ILocalizationService, LocalizationService>();
            services.AddTransient <ILocalizedEntityService, LocalizedEntityService>();
            services.AddTransient <IInstallationLocalizationService, InstallationLocalizationService>();
            services.AddTransient <ILanguageService, LanguageService>();
            services.AddTransient <IDownloadService, DownloadService>();
            services.AddTransient <IMessageTemplateService, MessageTemplateService>();
            services.AddTransient <IQueuedEmailService, QueuedEmailService>();
            services.AddTransient <INewsLetterSubscriptionService, NewsLetterSubscriptionService>();
            services.AddTransient <INotificationService, NotificationService>();
            services.AddTransient <ICampaignService, CampaignService>();
            services.AddTransient <IEmailAccountService, EmailAccountService>();
            services.AddTransient <IWorkflowMessageService, WorkflowMessageService>();
            services.AddTransient <IMessageTokenProvider, MessageTokenProvider>();
            services.AddTransient <ITokenizer, Tokenizer>();
            services.AddTransient <ISmtpBuilder, SmtpBuilder>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddTransient <ICheckoutAttributeFormatter, CheckoutAttributeFormatter>();
            services.AddTransient <ICheckoutAttributeParser, CheckoutAttributeParser>();
            services.AddTransient <ICheckoutAttributeService, CheckoutAttributeService>();
            services.AddTransient <IGiftCardService, GiftCardService>();
            services.AddTransient <IOrderService, OrderService>();
            services.AddTransient <IOrderReportService, OrderReportService>();
            services.AddTransient <IOrderProcessingService, OrderProcessingService>();
            services.AddTransient <IOrderTotalCalculationService, OrderTotalCalculationService>();
            services.AddTransient <IReturnRequestService, ReturnRequestService>();
            services.AddTransient <IRewardPointService, RewardPointService>();
            services.AddTransient <IShoppingCartService, ShoppingCartService>();
            services.AddTransient <ICustomNumberFormatter, CustomNumberFormatter>();
            services.AddTransient <IPaymentService, PaymentService>();
            services.AddTransient <IEncryptionService, EncryptionService>();
            services.AddTransient <IAuthenticationService, TestAuthenticationService>();
            services.AddTransient <IUrlRecordService, UrlRecordService>();
            services.AddTransient <IShipmentService, ShipmentService>();
            services.AddTransient <IShippingService, ShippingService>();
            services.AddTransient <IDateRangeService, DateRangeService>();
            services.AddTransient <ITaxCategoryService, TaxCategoryService>();
            services.AddTransient <ITaxService, TaxService>();
            services.AddTransient <ILogger, DefaultLogger>();
            services.AddTransient <ICustomerActivityService, CustomerActivityService>();
            services.AddTransient <IForumService, ForumService>();
            services.AddTransient <IGdprService, GdprService>();
            services.AddTransient <IPollService, PollService>();
            services.AddTransient <IBlogService, BlogService>();
            services.AddTransient <ITopicService, TopicService>();
            services.AddTransient <INewsService, NewsService>();
            services.AddTransient <IDateTimeHelper, DateTimeHelper>();
            services.AddTransient <ISitemapGenerator, SitemapGenerator>();
            services.AddTransient <IScheduleTaskService, ScheduleTaskService>();
            services.AddTransient <IExportManager, ExportManager>();
            services.AddTransient <IImportManager, ImportManager>();
            services.AddTransient <IPdfService, PdfService>();
            services.AddTransient <IUploadService, UploadService>();
            services.AddTransient <IThemeProvider, ThemeProvider>();
            services.AddTransient <IExternalAuthenticationService, ExternalAuthenticationService>();

            //slug route transformer
            services.AddSingleton <IReviewTypeService, ReviewTypeService>();
            services.AddSingleton <IEventPublisher, EventPublisher>();
            services.AddTransient <ISettingService, SettingService>();

            //plugin managers
            services.AddTransient(typeof(IPluginManager <>), typeof(PluginManager <>));
            services.AddTransient <IAuthenticationPluginManager, AuthenticationPluginManager>();
            services.AddTransient <IMultiFactorAuthenticationPluginManager, MultiFactorAuthenticationPluginManager>();
            services.AddTransient <IWidgetPluginManager, WidgetPluginManager>();
            services.AddTransient <IExchangeRatePluginManager, ExchangeRatePluginManager>();
            services.AddTransient <IDiscountPluginManager, DiscountPluginManager>();
            services.AddTransient <IPaymentPluginManager, PaymentPluginManager>();
            services.AddTransient <IPickupPluginManager, PickupPluginManager>();
            services.AddTransient <IShippingPluginManager, ShippingPluginManager>();
            services.AddTransient <ITaxPluginManager, TaxPluginManager>();

            services.AddTransient <IPictureService, TestPictureService>();

            //register all settings
            var settings = typeFinder.FindClassesOfType(typeof(ISettings), false).ToList();

            foreach (var setting in settings)
            {
                services.AddTransient(setting,
                                      context => context.GetRequiredService <ISettingService>().LoadSettingAsync(setting).Result);
            }

            //event consumers
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer <>)).ToList();

            foreach (var consumer in consumers)
            {
                foreach (var findInterface in consumer.FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IConsumer <>)))
                {
                    services.AddTransient(findInterface, consumer);
                }
            }

            services.AddSingleton <IInstallationService, InstallationService>();

            services
            // add common FluentMigrator services
            .AddFluentMigratorCore()
            .AddScoped <IProcessorAccessor, TestProcessorAccessor>()
            // set accessor for the connection string
            .AddScoped <IConnectionStringAccessor>(x => DataSettingsManager.LoadSettings())
            .AddScoped <IMigrationManager, MigrationManager>()
            .AddSingleton <IConventionSet, NopTestConventionSet>()
            .ConfigureRunner(rb =>
                             rb.WithVersionTable(new MigrationVersionInfo()).AddSQLite()
                             // define the assembly containing the migrations
                             .ScanIn(mAssemblies).For.Migrations());

            services.AddTransient <IStoreContext, WebStoreContext>();
            services.AddTransient <IWorkContext, WebWorkContext>();
            services.AddTransient <IThemeContext, ThemeContext>();

            services.AddTransient <IPageHeadBuilder, PageHeadBuilder>();

            //common factories
            services.AddTransient <IAclSupportedModelFactory, AclSupportedModelFactory>();
            services.AddTransient <IDiscountSupportedModelFactory, DiscountSupportedModelFactory>();
            services.AddTransient <ILocalizedModelFactory, LocalizedModelFactory>();
            services.AddTransient <IStoreMappingSupportedModelFactory, StoreMappingSupportedModelFactory>();

            //admin factories
            services.AddTransient <IBaseAdminModelFactory, BaseAdminModelFactory>();
            services.AddTransient <IActivityLogModelFactory, ActivityLogModelFactory>();
            services.AddTransient <IAddressAttributeModelFactory, AddressAttributeModelFactory>();
            services.AddTransient <IAffiliateModelFactory, AffiliateModelFactory>();
            services.AddTransient <IBlogModelFactory, BlogModelFactory>();
            services.AddTransient <ICampaignModelFactory, CampaignModelFactory>();
            services.AddTransient <ICategoryModelFactory, CategoryModelFactory>();
            services.AddTransient <ICheckoutAttributeModelFactory, CheckoutAttributeModelFactory>();
            services.AddTransient <ICommonModelFactory, CommonModelFactory>();
            services.AddTransient <ICountryModelFactory, CountryModelFactory>();
            services.AddTransient <ICurrencyModelFactory, CurrencyModelFactory>();
            services.AddTransient <ICustomerAttributeModelFactory, CustomerAttributeModelFactory>();
            services.AddTransient <ICustomerModelFactory, CustomerModelFactory>();
            services.AddTransient <ICustomerRoleModelFactory, CustomerRoleModelFactory>();
            services.AddTransient <IDiscountModelFactory, DiscountModelFactory>();
            services.AddTransient <IEmailAccountModelFactory, EmailAccountModelFactory>();
            services
            .AddTransient <IExternalAuthenticationMethodModelFactory, ExternalAuthenticationMethodModelFactory>();
            services.AddTransient <IForumModelFactory, ForumModelFactory>();
            services.AddTransient <IGiftCardModelFactory, GiftCardModelFactory>();
            services.AddTransient <IHomeModelFactory, HomeModelFactory>();
            services.AddTransient <ILanguageModelFactory, LanguageModelFactory>();
            services.AddTransient <ILogModelFactory, LogModelFactory>();
            services.AddTransient <IManufacturerModelFactory, ManufacturerModelFactory>();
            services.AddTransient <IMeasureModelFactory, MeasureModelFactory>();
            services.AddTransient <IMessageTemplateModelFactory, MessageTemplateModelFactory>();
            services.AddTransient <INewsletterSubscriptionModelFactory, NewsletterSubscriptionModelFactory>();
            services.AddTransient <INewsModelFactory, NewsModelFactory>();
            services.AddTransient <IOrderModelFactory, OrderModelFactory>();
            services.AddTransient <IPaymentModelFactory, PaymentModelFactory>();
            services.AddTransient <IPluginModelFactory, PluginModelFactory>();
            services.AddTransient <IPollModelFactory, PollModelFactory>();
            services.AddTransient <IProductModelFactory, ProductModelFactory>();
            services.AddTransient <IProductAttributeModelFactory, ProductAttributeModelFactory>();
            services.AddTransient <IProductReviewModelFactory, ProductReviewModelFactory>();
            services.AddTransient <IReportModelFactory, ReportModelFactory>();
            services.AddTransient <IQueuedEmailModelFactory, QueuedEmailModelFactory>();
            services.AddTransient <IRecurringPaymentModelFactory, RecurringPaymentModelFactory>();
            services.AddTransient <IReturnRequestModelFactory, ReturnRequestModelFactory>();
            services.AddTransient <IReviewTypeModelFactory, ReviewTypeModelFactory>();
            services.AddTransient <IScheduleTaskModelFactory, ScheduleTaskModelFactory>();
            services.AddTransient <ISecurityModelFactory, SecurityModelFactory>();
            services.AddTransient <ISettingModelFactory, SettingModelFactory>();
            services.AddTransient <IShippingModelFactory, ShippingModelFactory>();
            services.AddTransient <IShoppingCartModelFactory, ShoppingCartModelFactory>();
            services.AddTransient <ISpecificationAttributeModelFactory, SpecificationAttributeModelFactory>();
            services.AddTransient <IStoreModelFactory, StoreModelFactory>();
            services.AddTransient <ITaxModelFactory, TaxModelFactory>();
            services.AddTransient <ITemplateModelFactory, TemplateModelFactory>();
            services.AddTransient <ITopicModelFactory, TopicModelFactory>();
            services.AddTransient <IVendorAttributeModelFactory, VendorAttributeModelFactory>();
            services.AddTransient <IVendorModelFactory, VendorModelFactory>();
            services.AddTransient <IWidgetModelFactory, WidgetModelFactory>();

            //factories
            services.AddTransient <Web.Factories.IAddressModelFactory, Web.Factories.AddressModelFactory>();
            services.AddTransient <Web.Factories.IBlogModelFactory, Web.Factories.BlogModelFactory>();
            services.AddTransient <Web.Factories.ICatalogModelFactory, Web.Factories.CatalogModelFactory>();
            services.AddTransient <Web.Factories.ICheckoutModelFactory, Web.Factories.CheckoutModelFactory>();
            services.AddTransient <Web.Factories.ICommonModelFactory, Web.Factories.CommonModelFactory>();
            services.AddTransient <Web.Factories.ICountryModelFactory, Web.Factories.CountryModelFactory>();
            services.AddTransient <Web.Factories.ICustomerModelFactory, Web.Factories.CustomerModelFactory>();
            services.AddTransient <Web.Factories.IForumModelFactory, Web.Factories.ForumModelFactory>();
            services
            .AddTransient <Web.Factories.IExternalAuthenticationModelFactory,
                           Web.Factories.ExternalAuthenticationModelFactory>();
            services.AddTransient <Web.Factories.INewsModelFactory, Web.Factories.NewsModelFactory>();
            services.AddTransient <Web.Factories.INewsletterModelFactory, Web.Factories.NewsletterModelFactory>();
            services.AddTransient <Web.Factories.IOrderModelFactory, Web.Factories.OrderModelFactory>();
            services.AddTransient <Web.Factories.IPollModelFactory, Web.Factories.PollModelFactory>();
            services
            .AddTransient <Web.Factories.IPrivateMessagesModelFactory, Web.Factories.PrivateMessagesModelFactory>();
            services.AddTransient <Web.Factories.IProductModelFactory, Web.Factories.ProductModelFactory>();
            services.AddTransient <Web.Factories.IProfileModelFactory, Web.Factories.ProfileModelFactory>();
            services.AddTransient <Web.Factories.IReturnRequestModelFactory, Web.Factories.ReturnRequestModelFactory>();
            services.AddTransient <Web.Factories.IShoppingCartModelFactory, Web.Factories.ShoppingCartModelFactory>();
            services.AddTransient <Web.Factories.ITopicModelFactory, Web.Factories.TopicModelFactory>();
            services.AddTransient <Web.Factories.IVendorModelFactory, Web.Factories.VendorModelFactory>();
            services.AddTransient <Web.Factories.IWidgetModelFactory, Web.Factories.WidgetModelFactory>();

            _serviceProvider = services.BuildServiceProvider();

            EngineContext.Replace(new NopTestEngine(_serviceProvider));

            _serviceProvider.GetService <INopDataProvider>().CreateDatabase(null);
            _serviceProvider.GetService <INopDataProvider>().InitializeDatabase();

            var languagePackInfo = (DownloadUrl : string.Empty, Progress : 0);

            _serviceProvider.GetService <IInstallationService>()
            .InstallRequiredDataAsync(NopTestsDefaults.AdminEmail, NopTestsDefaults.AdminPassword, languagePackInfo, null, null).Wait();
            _serviceProvider.GetService <IInstallationService>().InstallSampleDataAsync(NopTestsDefaults.AdminEmail).Wait();

            var provider = (IPermissionProvider)Activator.CreateInstance(typeof(StandardPermissionProvider));

            EngineContext.Current.Resolve <IPermissionService>().InstallPermissionsAsync(provider).Wait();
        }
示例#36
0
        public TestEnv(
            string name,
            string rootPath,
            bool enableLazyOutputMaterialization = false,
            int maxRelativeOutputDirectoryLength = 260,
            List <IMount> mounts = null,
            PathTable pathTable  = null)
        {
            Contract.Requires(name != null);
            Contract.Requires(!string.IsNullOrEmpty(rootPath));

            LoggingContext = new LoggingContext("TestLogger." + name);
            PathTable      = pathTable ?? new PathTable();

            PipDataBuilderPool = new ObjectPool <PipDataBuilder>(() => new PipDataBuilder(PathTable.StringTable), _ => { });

            // The tests that use TestEnv need to be modernized to take a filesystem
            var fileSystem = new PassThroughFileSystem(PathTable);

            Context = EngineContext.CreateNew(CancellationToken.None, PathTable, fileSystem);

            // Add some well-known paths with fixed casing to the Context.PathTable
            AbsolutePath.Create(Context.PathTable, rootPath.ToLowerInvariant());
            var root = AbsolutePath.Create(Context.PathTable, rootPath);

            var configuration = ConfigHelpers.CreateDefaultForXml(Context.PathTable, root);

            configuration.Layout.SourceDirectory = root.Combine(PathTable, PathAtom.Create(PathTable.StringTable, "src")); // These tests have non-standard src folder
            configuration.Engine.MaxRelativeOutputDirectoryLength   = maxRelativeOutputDirectoryLength;
            configuration.Schedule.EnableLazyOutputMaterialization  = enableLazyOutputMaterialization;
            configuration.Schedule.UnsafeDisableGraphPostValidation = false;
            configuration.Schedule.ComputePipStaticFingerprints     = true;
            configuration.Sandbox.FileAccessIgnoreCodeCoverage      = true;

            BuildXLEngine.PopulateFileSystemCapabilities(configuration, configuration, Context.PathTable, LoggingContext);
            BuildXLEngine.PopulateLoggingAndLayoutConfiguration(configuration, Context.PathTable, bxlExeLocation: null, inTestMode: true);
            BuildXLEngine.PopulateAndValidateConfiguration(configuration, configuration, Context.PathTable, LoggingContext);

            Configuration = configuration;

            var mountsTable = MountsTable.CreateAndRegister(LoggingContext, Context, Configuration, null);

            if (mounts != null)
            {
                foreach (var mount in mounts)
                {
                    mountsTable.AddResolvedMount(mount);
                }
            }

            AbsolutePath specFile = SourceRoot.CreateRelative(Context.PathTable, "TestSpecFile.dsc");

            var graph = TestSchedulerFactory.CreateEmptyPipGraph(Context, configuration, mountsTable.MountPathExpander);

            PipTable = graph.PipTable;
            PipGraph = graph;

            var locationData = new LocationData(specFile, 0, 0);
            var modulePip    = ModulePip.CreateForTesting(Context.StringTable, specFile);

            PipGraph.AddModule(modulePip);
            PipGraph.AddSpecFile(new SpecFilePip(FileArtifact.CreateSourceFile(specFile), locationData, modulePip.Module));

            PipConstructionHelper = PipConstructionHelper.CreateForTesting(
                Context,
                ObjectRoot,
                redirectedRoot: Configuration.Layout.RedirectedDirectory,
                pipGraph: PipGraph,
                moduleName: modulePip.Identity.ToString(Context.StringTable),
                symbol: name,
                specPath: specFile);

            Paths = new Paths(PathTable);

            mountsTable.CompleteInitialization();
        }
示例#37
0
        private static bool TryBuildPipGraphFragment(
            ICommandLineConfiguration commandLineConfig,
            PipGraphFragmentGeneratorConfiguration pipGraphFragmentGeneratorConfig,
            FrontEndContext frontEndContext,
            EngineContext engineContext,
            EvaluationFilter evaluationFilter)
        {
            Contract.Requires(frontEndContext != null);
            Contract.Requires(engineContext != null);
            Contract.Requires(commandLineConfig.Startup.ConfigFile.IsValid);
            Contract.Requires(evaluationFilter != null);

            var pathTable      = engineContext.PathTable;
            var loggingContext = frontEndContext.LoggingContext;

            var mutableCommandlineConfig = CompleteCommandLineConfiguration(commandLineConfig);

            BuildXLEngine.ModifyConfigurationForCloudbuild(mutableCommandlineConfig, false, pathTable, loggingContext);
            BuildXLEngine.PopulateLoggingAndLayoutConfiguration(mutableCommandlineConfig, pathTable, bxlExeLocation: null);

            var statistics = new FrontEndStatistics();
            var frontEndControllerFactory = FrontEndControllerFactory.Create(
                mode: FrontEndMode.NormalMode,
                loggingContext: loggingContext,
                configuration: mutableCommandlineConfig,
                collector: null,
                statistics: statistics);

            var controller = frontEndControllerFactory.Create(engineContext.PathTable, engineContext.SymbolTable);

            controller.InitializeHost(frontEndContext, mutableCommandlineConfig);

            FrontEndHostController frontEndHostController = (FrontEndHostController)controller;

            var config = controller.ParseConfig(mutableCommandlineConfig);

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

            using (var cache = Task.FromResult <Possible <EngineCache> >(
                       new EngineCache(
                           new InMemoryArtifactContentCache(),
                           new EmptyTwoPhaseFingerprintStore())))
            {
                var mountsTable = MountsTable.CreateAndRegister(loggingContext, engineContext, config, mutableCommandlineConfig.Startup.Properties);
                FrontEndEngineAbstraction frontEndEngineAbstraction = new FrontEndEngineImplementation(
                    loggingContext,
                    frontEndContext.PathTable,
                    config,
                    mutableCommandlineConfig.Startup,
                    mountsTable,
                    InputTracker.CreateDisabledTracker(loggingContext),
                    null,
                    null,
                    () => FileContentTable.CreateStub(loggingContext),
                    5000,
                    false,
                    controller.RegisteredFrontEnds);

                var pipGraphBuilder = pipGraphFragmentGeneratorConfig.TopSort
                    ? new PipGraphFragmentBuilderTopSort(engineContext, config, mountsTable.MountPathExpander)
                    : new PipGraphFragmentBuilder(engineContext, config, mountsTable.MountPathExpander);

                if (!AddConfigurationMountsAndCompleteInitialization(config, loggingContext, mountsTable))
                {
                    return(false);
                }

                if (!mountsTable.PopulateModuleMounts(config.ModulePolicies.Values, out var moduleMountsTableMap))
                {
                    Contract.Assume(loggingContext.ErrorWasLogged, "An error should have been logged after MountTable.PopulateModuleMounts()");
                    return(false);
                }

                using (frontEndEngineAbstraction is IDisposable ? (IDisposable)frontEndEngineAbstraction : null)
                {
                    if (!controller.PopulateGraph(
                            cache: cache,
                            graph: pipGraphBuilder,
                            engineAbstraction: frontEndEngineAbstraction,
                            evaluationFilter: evaluationFilter,
                            configuration: config,
                            startupConfiguration: mutableCommandlineConfig.Startup))
                    {
                        // Error should have been reported already
                        return(false);
                    }

                    if (!SerializeFragmentIfRequested(pipGraphFragmentGeneratorConfig, frontEndContext, pipGraphBuilder))
                    {
                        // Error should have been reported already
                        return(false);
                    }
                }
            }

            return(true);
        }
示例#38
0
        protected void Application_Start()
        {
            // we use our own mobile devices support (".Mobile" is reserved). that's why we disable it.
            var mobileDisplayMode = DisplayModeProvider.Instance.Modes.FirstOrDefault(x => x.DisplayModeId == DisplayModeProvider.MobileDisplayModeId);

            if (mobileDisplayMode != null)
            {
                DisplayModeProvider.Instance.Modes.Remove(mobileDisplayMode);
            }

            bool installed = DataSettings.DatabaseIsInstalled();

            if (installed)
            {
                // Remove all view engines
                ViewEngines.Engines.Clear();
            }

            // Initialize engine context
            var engine = EngineContext.Initialize(false);

            // Model binders
            ModelBinders.Binders.DefaultBinder = new SmartModelBinder();

            // Add some functionality on top of the default ModelMetadataProvider
            ModelMetadataProviders.Current = new SmartMetadataProvider();

            // Register MVC areas
            AreaRegistration.RegisterAllAreas();

            // Fluent validation
            FluentValidationModelValidatorProvider.Configure(x =>
            {
                x.ValidatorFactory = new SmartValidatorFactory();
            });

            // Routes
            RegisterRoutes(RouteTable.Routes, engine, installed);

            // localize MVC resources
            ClientDataTypeModelValidatorProvider.ResourceClassKey = "MvcLocalization";
            DefaultModelBinder.ResourceClassKey = "MvcLocalization";
            ErrorMessageProvider.SetResourceClassKey("MvcLocalization");

            // Register JsEngine
            RegisterJsEngines();

            // VPPs
            RegisterVirtualPathProviders();

            if (installed)
            {
                // register our themeable razor view engine we use
                ViewEngines.Engines.Add(new ThemeableRazorViewEngine());

                // Global filters
                RegisterGlobalFilters(GlobalFilters.Filters, engine);

                // Bundles
                RegisterBundles(BundleTable.Bundles, engine);

                // "throw-away" filter for task scheduler initialization (the filter removes itself when processed)
                GlobalFilters.Filters.Add(new InitializeSchedulerFilter(), int.MinValue);

                // register AutoMapper class maps
                RegisterClassMaps(engine);
            }
            else
            {
                // app not installed

                // Install filter
                GlobalFilters.Filters.Add(new HandleInstallFilter());
            }
        }
示例#39
0
 public void TearDown()
 {
     EngineContext.Replace(null);
 }
示例#40
0
        public static async Task AnimateIntroAndEndScene(EngineContext engineContext)
        {
            var yebisPlugin = engineContext.RenderContext.RenderPassPlugins.OfType<YebisPlugin>().FirstOrDefault();
            var slideShowPlugin = engineContext.RenderContext.RenderPassPlugins.OfType<SlideShowPlugin>().FirstOrDefault();

            // Return immediately if there is no Yebis
            if (yebisPlugin == null || slideShowPlugin == null)
            {
                return;
            }

            var xenkoLogo = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/LogoXenko.dds");
            var xenkoLogoURL = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/LogoXenkoURL.dds");

            slideShowPlugin.TextureFrom = xenkoLogo;
            slideShowPlugin.TextureTo = xenkoLogoURL;
            slideShowPlugin.RenderPass.Enabled = false;

            double lastTime = 0;
            float lastExposure = 0.0f;

            yebisPlugin.ToneMap.AutoExposure.Enable = true;

            var savedToneMap = yebisPlugin.ToneMap;
            var savedLens = yebisPlugin.Lens;
            var savedColorCorrection = yebisPlugin.ColorCorrection;

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                var animationTime = (float)engineContext.CurrentTime.TotalSeconds % CaveSceneRestart;

                var deltaTime = (float)(animationTime - lastTime);

                // If scene restart
                if (deltaTime < 0.0f)
                {
                    yebisPlugin.ToneMap = savedToneMap;
                    yebisPlugin.Lens = savedLens;
                    yebisPlugin.ColorCorrection = savedColorCorrection;

                    // Enable all
                    foreach (var pass in engineContext.RenderContext.RootRenderPass.Passes)
                    {
                        if (pass.Name == "WireframePass")
                            continue;
                        pass.Enabled = true;
                    }
                    // Disable SlideShow
                    slideShowPlugin.RenderPass.Enabled = false;
                    yebisPlugin.ToneMap.Exposure = 0.005f;
                    yebisPlugin.ToneMap.AutoExposure.Enable = true;
                    slideShowPlugin.TransitionFactor = 0.0f;
                }

                // If we reset, reupload the particle buffer
                if (animationTime < FullExposureTime)
                {
                    yebisPlugin.ToneMap.AutoExposure.Enable = true;
                }
                else if (animationTime < LogoTimeBegin)
                {
                    if (yebisPlugin.ToneMap.AutoExposure.Enable)
                    {
                        lastExposure = yebisPlugin.ToneMap.Exposure;
                        yebisPlugin.ToneMap.AutoExposure.Enable = false;
                    }

                    yebisPlugin.ToneMap.Exposure = lastExposure + (60.0f - lastExposure) *  (float)Math.Pow((animationTime - FullExposureTime) / (LogoTimeBegin - FullExposureTime), 2.0f);
                }
                else 
                {
                    if (!slideShowPlugin.RenderPass.Enabled)
                    {
                        // Enable only Yebis and SlideShow
                        foreach (var pass in engineContext.RenderContext.RootRenderPass.Passes)
                        {
                            pass.Enabled = false;
                        }
                        yebisPlugin.RenderPass.Enabled = true;
                        slideShowPlugin.RenderPass.Enabled = true;

                        yebisPlugin.ToneMap.Type = ToneMapType.Linear;
                        yebisPlugin.Lens.Vignette.Enable = false;
                        yebisPlugin.ToneMap.Gamma = 1.0f;
                        yebisPlugin.ColorCorrection.ColorTemperature = 6500;
                        yebisPlugin.ColorCorrection.Saturation = 1.0f;
                        yebisPlugin.ColorCorrection.Contrast = 1.0f;
                        yebisPlugin.ColorCorrection.Brightness = 1.0f;
                        lastExposure = yebisPlugin.ToneMap.Exposure;
                        slideShowPlugin.TransitionFactor = 0.0f;
                    }

                    if (animationTime < LogoTimeFull)
                    {
                        slideShowPlugin.ZoomFactor = 0.5f + (1.0f - 0.5f) * Quintic((animationTime - LogoTimeBegin) / (LogoTimeFull - LogoTimeBegin));
                        yebisPlugin.ToneMap.Exposure = lastExposure + (1.0f - lastExposure) * (float)Math.Pow((animationTime - LogoTimeBegin) / (LogoTimeFull - LogoTimeBegin), 0.1f);
                    }
                    else
                    {
                        slideShowPlugin.ZoomFactor = 1.0f;
                        if (animationTime < LogoTimeURL)
                        {
                            yebisPlugin.ToneMap.Exposure = 1.0f;
                        }
                        else if (animationTime < LogoTimeStartToEnd)
                        {
                            slideShowPlugin.TransitionFactor = Math.Min(1.0f, (animationTime - LogoTimeURL) / (LogoTimeStartToEnd - LogoTimeURL));
                        }
                        else if (animationTime < LogoTimeEnd)
                        {
                            slideShowPlugin.TransitionFactor = 1.0f;
                        }
                        else if (animationTime < CaveSceneEndBlack)
                        {
                            yebisPlugin.ToneMap.Exposure = Math.Max(0.0f, 1.0f - (animationTime - LogoTimeEnd) / (CaveSceneEndBlack - LogoTimeEnd));
                        }
                        else
                        {
                            yebisPlugin.ToneMap.Exposure = 0f;
                        }
                    }
                }
                //Console.WriteLine("Exposure: {0}", yebisPlugin.ToneMap.Exposure);

                lastTime = animationTime;
            }
        }
示例#41
0
        public static async Task AnimateLight(EngineContext engineContext, int index, LightComponent lightComponent)
        {
            // Wait different time for each light
            await TaskEx.Delay(index * 20);
            var startIntensity = lightComponent.Intensity;

            // Turn light off
            var startTime = DateTime.UtcNow;
            while (true)
            {
                await engineContext.Scheduler.NextFrame();
                var elapsedTime = (DateTime.UtcNow - startTime).Seconds * 0.2f;
                if (elapsedTime > 1.0f)
                    break;
                lightComponent.Intensity = startIntensity * (1.0f - elapsedTime);
            }

            // Turn light on
       
            lightComponent.Intensity = startIntensity;
        }
示例#42
0
        // [XenkoScript]
        public static async Task LoadCave(EngineContext engineContext, Entity animationEntity)
        {
            // Setup "fake" directional light for outdoor so that normal maps stand out.
            var outdoorLight = new DirectionalLight { LightDirection = new Vector3(-2.0f, -1.0f, -1.0f) };
            //outdoor.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = { outdoorLight } });
            //outdoor.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = { outdoorLight } });

            var effectMagma = engineContext.RenderContext.Effects.First(x => x.Name == "Magma");

            effectMagma.Parameters.AddSources(engineContext.DataContext.RenderPassPlugins.TryGetValue("NoisePlugin").Parameters);

            //var assetManager = new AssetManager(new ContentSerializerContextGenerator(engineContext.VirtualFileSystem, engineContext.PackageManager, ParameterContainerExtensions.DefaultSceneSerializer));
            var caveEntityPrefab1 = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/bg/bg1.hotei#");
            var caveEntityPrefab2 = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/bg/bg2.hotei#");

            var caveEntity1 = Prefab.Clone(caveEntityPrefab1);
            var caveEntity2 = Prefab.Clone(caveEntityPrefab2);

            SkyBoxPlugin skyBoxPlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin))
            {
                var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds");
                skyBoxPlugin.Texture = skyBoxTexture;
            }

            var magmaTexturePaths = new[]
                {
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_04.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_05.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_06.dds",

                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_00.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_01.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_02.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_03.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_noise_00.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_noise_01.dds",
                    "/global_data/gdc_demo/bg/GDC2012_map_maguma_normals.dds",
                };
            var magmaTextures = new Texture2D[magmaTexturePaths.Length];
            for (int i = 0; i < magmaTextures.Length; i++)
            {
                magmaTextures[i] = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>(magmaTexturePaths[i]);
            }

            var lightVectors = new[]
                {
                    new Vector3(-1.0f, 0.3f, -1.0f),
                    new Vector3(1.0f, 0.0f, -1.0f),
                    new Vector3(1.0f, 0.0f, -1.0f),
                };


            var random = new Random(0);
            int planeIndex = 0;
            foreach (var entity in ParameterContainerExtensions.CollectEntityTree(caveEntity1))
            {
                var meshComponent = entity.Get(ModelComponent.Key);
                if (meshComponent == null)
                    continue;

                // Setup textures for magma
                if (entity.Name.StartsWith("maguma_"))
                {
                    meshComponent.MeshParameters.Set(LightKeys.LightDirection, lightVectors[planeIndex]);
                    meshComponent.MeshParameters.Set(ParameterKeys.IndexedKey(TexturingKeys.Texture0, 1), magmaTextures[planeIndex]);
                    planeIndex++;
                    for (int i = 3; i < magmaTextures.Length; i++)
                        meshComponent.MeshParameters.Set(ParameterKeys.IndexedKey(TexturingKeys.Texture0, i - 1), magmaTextures[i]);


                    foreach (var effectMesh in meshComponent.SubMeshes)
                    {
                        effectMesh.EffectData.Name = "Magma";
                    }

                    // Attach a bullet particle emitter to the magma
                    var emitter = new BulletParticleEmitterComponent()
                    {
                        //Count = 4096,
                        Count = 16384,
                        Description = new BulletEmitterDescription()
                        {
                            Target = new Vector3(-3016.261f, -70.52288f, 800.8788f),
                            BulletSize = 4.0f,
                            //MaxTimeTarget = 1000.0f + 5000.0f * (float)random.NextDouble(),
                            VelocityUp =  new Vector3(0, 0, 200),
                            MaxTimeUp = 5000.0f,
                            MaxTimeTarget = 20000.0f,
                            VelocityTarget = 200.0f,
                            Opacity = 1.0f,
                            //DistanceDragonRepulse = 1200.0f,
                            //DecayDragonRepulse = 70.0f,
                            DistanceDragonRepulse = 600.0f,
                            DecayDragonRepulse = 70.0f,
                            VelocityRepulse = 200.0f,
                        },
                        RootAnimation = animationEntity,
                    };
                    emitter.OnAddToSystem(engineContext.EntityManager, engineContext.RenderContext);
                    emitter.OnUpdateData();
                    entity.Set(ParticleEmitterComponent.Key, emitter);
                }

                foreach (var effectMesh in meshComponent.SubMeshes)
                {
                    effectMesh.Parameters.Set(ParameterKeys.IndexedKey(TexturingKeys.DiffuseTexture, 3), (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/GDC2012_map_dis_ao.dds"));
                }
            }

            await engineContext.EntityManager.AddEntityAsync(caveEntity1);
            await engineContext.EntityManager.AddEntityAsync(caveEntity2);

            foreach (var entity in ParameterContainerExtensions.CollectEntityTree(caveEntity1).Concat(ParameterContainerExtensions.CollectEntityTree(caveEntity2)))
            {
                var meshComponent = entity.Get(ModelComponent.Key);
                if (meshComponent == null)
                    continue;

                foreach (var effectMesh in meshComponent.InstantiatedSubMeshes)
                {
                    effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 2.0f);
                    effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.1f);
                }
            }
        }
示例#43
0
        public static async Task LoadDude(EngineContext engineContext)
        {
            var mainPlugin = engineContext.RenderContext.RenderPassPlugins.OfType<MainPlugin>().FirstOrDefault();
            EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleSkinning")
                .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = mainPlugin })
                .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = mainPlugin })
                    .Using(new BasicShaderPlugin(new ShaderMixinSource() {
                            new ShaderClassSource("AlbedoDiffuseBase"),
                            new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorTexture", TexturingKeys.DiffuseTexture, "TEXCOORD")),
                            new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values!
                    }) { RenderPassPlugin = mainPlugin })
                .Using(new BasicShaderPlugin("AlbedoFlatShading") { RenderPassPlugin = mainPlugin })
                ;

            var characterEntity = await AnimScript.LoadFBXModel(engineContext, "/global_data/fbx/test_mesh.hotei#");
            await AnimScript.AnimateFBXModel(engineContext, characterEntity);
        }
示例#44
0
        public decimal FoodSatisfactionRate = 1; // The rate at which hunger is reduced upon consumption

        #endregion Fields

        #region Constructors

        public EatActivity(Person person, EngineContext context)
            : base(ActivityType.Eating, person, context)
        {
        }
示例#45
0
        private static void SetupParticles(EngineContext engineContext)
        {
            // Create particle system
            var particleSystem = new SiliconStudio.Xenko.Particles.ParticleSystem();

            // Set particle default size to 10.0f
            particleSystem.GetOrCreateFieldWithDefault(ParticleFields.Size, 10.0f);

            // Add particle plugins
            particleSystem.Plugins.Add(new ResetAcceleration());
            particleSystem.Plugins.Add(new SimpleEmitter());
            particleSystem.Plugins.Add(new RemoveOldParticles(10.0f));
            particleSystem.Plugins.Add(new Gravity());
            particleSystem.Plugins.Add(new UpdateVelocity());

            // Create particle system mesh for rendering.
            var particleEffect = engineContext.RenderContext.Effects.First(x => x.Name == "DefaultParticle");
            var particleMesh = new EffectMesh(particleEffect);
            particleMesh.Parameters.Set(ParticleRendererPlugin.ParticleSystemKey, particleSystem);

            // Load particle texture
            var smokeVolTexture = (Texture2D)engineContext.AssetManager.Load<Texture>("/global_data/gdc_demo/fx/smokevol.dds");
            particleMesh.Parameters.Set(TexturingKeys.DiffuseTexture, smokeVolTexture);

            // Register it to rendering
            engineContext.RenderContext.GlobalMeshes.AddMesh(particleMesh);
        }
        public new void SetUp()
        {
            var cacheManager = new NopNullCache();

            _workContext = MockRepository.GenerateMock <IWorkContext>();
            _workContext.Expect(w => w.WorkingCurrency).Return(new Currency {
                RoundingType = RoundingType.Rounding001
            });

            _currencySettings = new CurrencySettings();
            var currency1 = new Currency
            {
                Id               = 1,
                Name             = "Euro",
                CurrencyCode     = "EUR",
                DisplayLocale    = "",
                CustomFormatting = "€0.00",
                DisplayOrder     = 1,
                Published        = true,
                CreatedOnUtc     = DateTime.UtcNow,
                UpdatedOnUtc     = DateTime.UtcNow
            };
            var currency2 = new Currency
            {
                Id               = 1,
                Name             = "US Dollar",
                CurrencyCode     = "USD",
                DisplayLocale    = "en-US",
                CustomFormatting = "",
                DisplayOrder     = 2,
                Published        = true,
                CreatedOnUtc     = DateTime.UtcNow,
                UpdatedOnUtc     = DateTime.UtcNow
            };

            _currencyRepo = MockRepository.GenerateMock <IRepository <Currency> >();
            _currencyRepo.Expect(x => x.Table).Return(new List <Currency> {
                currency1, currency2
            }.AsQueryable());

            _storeMappingService = MockRepository.GenerateMock <IStoreMappingService>();

            var pluginFinder = new PluginFinder();

            _currencyService = new CurrencyService(cacheManager, _currencyRepo, _storeMappingService,
                                                   _currencySettings, pluginFinder, null);

            _taxSettings = new TaxSettings();

            _localizationService = MockRepository.GenerateMock <ILocalizationService>();
            _localizationService.Expect(x => x.GetResource("Products.InclTaxSuffix", 1, false)).Return("{0} incl tax");
            _localizationService.Expect(x => x.GetResource("Products.ExclTaxSuffix", 1, false)).Return("{0} excl tax");

            _priceFormatter = new PriceFormatter(_workContext, _currencyService, _localizationService,
                                                 _taxSettings, _currencySettings);

            var nopEngine        = MockRepository.GenerateMock <NopEngine>();
            var containe         = MockRepository.GenerateMock <IContainer>();
            var containerManager = MockRepository.GenerateMock <ContainerManager>(containe);

            nopEngine.Expect(x => x.ContainerManager).Return(containerManager);
            containerManager.Expect(x => x.Resolve <IWorkContext>()).Return(_workContext);
            EngineContext.Replace(nopEngine);
        }
示例#47
0
 public static async Task Run(EngineContext engineContext)
 {
     await TaskEx.Delay(1000);
 }
示例#48
0
 public GardenActivity(Person person, EngineContext context)
     : base(ActivityType.Gardening, person, context)
 {
 }
        static void GetVersion()
        {
            var result = EngineContext.Resolve <PluginProcessor>().GetVersion();

            Console.WriteLine(result);
        }
 public DataCompanyController(EngineContext _context, IEngineDb _Metodo, IEngineLogical _Funcion)
 {
     context = _context;
     Metodo  = _Metodo;
     Funcion = _Funcion;
 }
示例#51
0
        public async Task ProcessGizmoAndPicking(EngineContext engineContext)
        {
            var gizmoTargetPlugin = (RenderTargetsPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GizmoTargetPlugin");

            if (gizmoTargetPlugin == null)
            {
                return;
            }

            var pickingResults = new Queue <PickingAction>();

            var effectGizmo = engineContext.RenderContext.BuildEffect("Gizmo")
                              .Using(
                new BasicShaderPlugin(
                    new ShaderMixinSource()
            {
                "ShaderBase",
                "TransformationWVP",
                "AlbedoFlatShading",
            })
            {
                RenderPassPlugin = gizmoTargetPlugin
            })
                              .Using(new MaterialShaderPlugin()
            {
                RenderPassPlugin = gizmoTargetPlugin
            })
                              //.Using(new LightingShaderPlugin() { RenderPassPlugin = renderingSetup.LightingPlugin })
            ;

            effectGizmo.PickingPassMainPlugin = gizmoTargetPlugin;

            //effectGizmo.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = new Light[] { new DirectionalLight { LightColor = new Color3(1.0f), LightDirection = new R32G32B32_Float(-1.0f, -1.0f, 1.0f) } } });

            engineContext.RenderContext.Effects.Add(effectGizmo);

            editorEntitySystem = new EntitySystem();
            editorEntitySystem.Processors.Add(new MeshProcessor(engineContext.RenderContext, engineContext.AssetManager));
            editorEntitySystem.Processors.Add(new HierarchicalProcessor());
            editorEntitySystem.Processors.Add(new TransformationProcessor());
            editorEntitySystem.Processors.Add(new TransformationUpdateProcessor());

            // Prepare gizmo entities
            translationGizmo = GenerateTranslationGizmo();
            rotationGizmo    = GenerateRotationGizmo();
            UpdateGizmoHighlighting(GizmoAction.None);

            RenderPassPlugin renderPassPlugin;

            engineContext.DataContext.RenderPassPlugins.TryGetValue("PickingPlugin", out renderPassPlugin);
            var pickingPlugin = renderPassPlugin as PickingPlugin;

            engineContext.DataContext.RenderPassPlugins.TryGetValue("MouseOverPickingPlugin", out renderPassPlugin);
            var mouseOverPickingPlugin = renderPassPlugin as PickingPlugin;

            // States
            var    pickingGizmoOrigin    = new Vector3();
            var    previousMouseLocation = new Vector2();
            var    currentGizmoAction    = GizmoAction.None;
            var    nextGizmoAction       = GizmoAction.None;
            Entity nextSelectedEntity    = null;

            var previousMousePosition = Vector2.Zero;

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                lock (pickingResults)
                {
                    var mousePosition = engineContext.InputManager.MousePosition;
                    if (engineContext.InputManager.IsMouseButtonPressed(MouseButton.Left))
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type          = PickingActionType.MouseDown,
                            MouseLocation = mousePosition,
                            PickingResult = pickingPlugin.Pick(engineContext.InputManager.MousePosition),
                        });
                    }
                    else if (engineContext.InputManager.IsMouseButtonReleased(MouseButton.Left))
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type          = PickingActionType.MouseUp,
                            MouseLocation = mousePosition,
                        });
                    }

                    if (engineContext.InputManager.IsMouseButtonDown(MouseButton.Left) && previousMousePosition != mousePosition)
                    {
                        pickingResults.Enqueue(new PickingAction
                        {
                            Type          = PickingActionType.MouseMove,
                            MouseLocation = mousePosition,
                        });
                    }

                    pickingResults.Enqueue(new PickingAction
                    {
                        Type          = PickingActionType.MouseOver,
                        MouseLocation = mousePosition,
                        PickingResult = mouseOverPickingPlugin.Pick(mousePosition)
                    });

                    previousMousePosition = mousePosition;

                    while (pickingResults.Count > 0 && (pickingResults.Peek().PickingResult == null || pickingResults.Peek().PickingResult.IsCompleted))
                    {
                        // State machine handling mouse down/move/over. Everything work in async deferred (picking results only comes after a few frames due to GPU asynchronism).
                        // Possible improvements:
                        // - If user do a mouse down and no gizmo action active, it should either be gizmo action if selected item didn't change, or instant picking (no wait for mouse up) if picking changed.
                        //   Gizmo action could probably start on new entity if MouseMove happens during the same sequence.
                        var pickingAction = pickingResults.Dequeue();
                        var pickedEntity  = pickingAction.PickingResult != null?GetPickedEntity(engineContext, pickingAction.PickingResult.Result.EffectMesh) : null;

                        switch (pickingAction.Type)
                        {
                        case PickingActionType.MouseOver:
                            if (currentGizmoAction == GizmoAction.None)
                            {
                                // Mouse over or click on gizmo: highlight the appropriate parts (yellow)
                                nextGizmoAction = pickedEntity != null?pickedEntity.Get(GizmoActionKey) : GizmoAction.None;

                                UpdateGizmoHighlighting(nextGizmoAction);
                                if (pickedEntity != null)
                                {
                                    pickingGizmoOrigin = pickingAction.PickingResult.Result.Position;
                                }
                            }
                            break;

                        case PickingActionType.MouseDown:
                            nextSelectedEntity    = pickedEntity;
                            previousMouseLocation = pickingAction.MouseLocation;

                            // User isn't around a "mouse over gizmo" so it is a picking selection for sure, doesn't wait for mouse move or mouse up
                            if (nextGizmoAction == GizmoAction.None)
                            {
                                UpdateSelectedEntities(engineContext, nextSelectedEntity);

                                // Force gizmo refresh (otherwise it won't happen as we enforce gizmo action right away, however we don't want it to be highlighted until used)
                                RefreshGizmos(GizmoAction.None);
                                UpdateGizmoHighlighting(currentGizmoAction);

                                // Engage default action
                                if (currentActiveGizmoActionMode == GizmoAction.Translation)
                                {
                                    currentGizmoAction = GizmoAction.TranslationXY;
                                    if (pickedEntity != null)
                                    {
                                        pickingGizmoOrigin = pickingAction.PickingResult.Result.Position;
                                    }
                                }
                                else if (currentGizmoAction == GizmoAction.Rotation)
                                {
                                    currentGizmoAction = GizmoAction.RotationZ;
                                }
                            }

                            if (selectedEntities != null && selectedEntities.Length > 0)
                            {
                                // Save aside picking object origin in case it turns out to be a translation
                                foreach (var selectedEntity in selectedEntities)
                                {
                                    var transformationComponent = selectedEntity.Entity.Transformation.Value as TransformationTRS;
                                    selectedEntity.PickingObjectOrigin = transformationComponent != null ? transformationComponent.Translation : Vector3.Zero;
                                }
                            }
                            break;

                        case PickingActionType.MouseMove:
                            // Gizmo action just started?
                            if (currentGizmoAction == GizmoAction.None)
                            {
                                currentGizmoAction = nextGizmoAction;
                            }
                            UpdateGizmoHighlighting(currentGizmoAction);
                            if (selectedEntities != null && selectedEntities.Length > 0)
                            {
                                // Performs translation
                                if ((currentGizmoAction & GizmoAction.Translation) != GizmoAction.None)
                                {
                                    // Translation is computed from origin position during mouse down => mouse delta is not reset
                                    foreach (var selectedEntity in selectedEntities)
                                    {
                                        MoveEntity(engineContext, selectedEntity.Entity, currentGizmoAction, pickingGizmoOrigin, selectedEntity.PickingObjectOrigin, pickingAction.MouseLocation - previousMouseLocation);
                                    }
                                }
                                else if ((currentGizmoAction & GizmoAction.Rotation) != GizmoAction.None)
                                {
                                    foreach (var selectedEntity in selectedEntities)
                                    {
                                        RotateEntity(engineContext, selectedEntity.Entity, currentGizmoAction, pickingAction.MouseLocation - previousMouseLocation);
                                    }
                                    // Rotation is using incremental => reset delta
                                    previousMouseLocation = pickingAction.MouseLocation;
                                }
                            }
                            break;

                        case PickingActionType.MouseUp:
                            if (currentGizmoAction == GizmoAction.None)
                            {
                                // Selection
                                UpdateSelectedEntities(engineContext, nextSelectedEntity);
                            }

                            // Reset states
                            currentGizmoAction = GizmoAction.None;
                            nextGizmoAction    = GizmoAction.None;
                            UpdateGizmoHighlighting(nextGizmoAction);
                            nextSelectedEntity = null;
                            break;
                        }
                    }
                }

                if (currentGizmoAction == GizmoAction.None)
                {
                    if (!EnumerableExtensions.Equals(SelectedEntities, selectedEntities != null ? selectedEntities.Select(x => x.Entity) : null))
                    {
                        selectedEntities = SelectedEntities.Select(x => new SelectedEntity(x)).ToArray();
                    }
                }

                RefreshGizmos(currentGizmoAction);
                editorEntitySystem.Update();
            }
        }
示例#52
0
        public static bool TryBuildWorkspace(
            ICommandLineConfiguration commandLineConfig,
            FrontEndContext frontEndContext,
            EngineContext engineContext,
            EvaluationFilter evaluationFilter,
            EventHandler <WorkspaceProgressEventArgs> progressHandler,
            out Workspace workspace,
            out FrontEndHostController frontEndHostController,
            out IPipGraph pipGraph,
            WorkspaceBuilderConfiguration configuration,
            FrontEndEngineAbstraction frontEndEngineAbstraction = null,
            bool collectMemoryAsSoonAsPossible = true)
        {
            Contract.Requires((commandLineConfig.Engine.Phase & (EnginePhases.ParseWorkspace | EnginePhases.AnalyzeWorkspace)) != EnginePhases.None);
            Contract.Requires(frontEndContext != null);
            Contract.Requires(engineContext != null);
            Contract.Requires(commandLineConfig.Startup.ConfigFile.IsValid);
            Contract.Requires(evaluationFilter != null);

            workspace = null;
            frontEndHostController = null;
            pipGraph = null;

            var pathTable      = engineContext.PathTable;
            var loggingContext = frontEndContext.LoggingContext;

            var mutableCommandlineConfig = GetCommandLineConfiguration(
                commandLineConfig,
                configuration);

            BuildXLEngine.ModifyConfigurationForCloudbuild(mutableCommandlineConfig, false, pathTable, loggingContext);
            BuildXLEngine.PopulateLoggingAndLayoutConfiguration(mutableCommandlineConfig, pathTable, bxlExeLocation: null);

            var statistics = new FrontEndStatistics(progressHandler);
            var frontEndControllerFactory = FrontEndControllerFactory.Create(
                mode: FrontEndMode.NormalMode,
                loggingContext: loggingContext,
                configuration: mutableCommandlineConfig,
                collector: null,
                statistics: statistics,
                collectMemoryAsSoonAsPossible: collectMemoryAsSoonAsPossible);

            var controller = frontEndControllerFactory.Create(engineContext.PathTable, engineContext.SymbolTable);

            controller.InitializeHost(frontEndContext, mutableCommandlineConfig);

            frontEndHostController = (FrontEndHostController)controller;

            // If there is an explicit engine abstraction, we set it. This is used by IDE test.
            if (frontEndEngineAbstraction != null)
            {
                frontEndHostController.SetState(frontEndEngineAbstraction, pipGraph: null, configuration: mutableCommandlineConfig);
            }

            var config = controller.ParseConfig(mutableCommandlineConfig);

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

            IPipGraph pipGraphBuilder = null;

            using (var cache = Task.FromResult <Possible <EngineCache> >(
                       new EngineCache(
                           new InMemoryArtifactContentCache(),

                           // Note that we have an 'empty' store (no hits ever) rather than a normal in memory one.
                           new EmptyTwoPhaseFingerprintStore())))
            {
                if (frontEndEngineAbstraction == null)
                {
                    if (mutableCommandlineConfig.Engine.Phase.HasFlag(EnginePhases.Schedule))
                    {
                        var mountsTable = MountsTable.CreateAndRegister(loggingContext, engineContext, config, mutableCommandlineConfig.Startup.Properties);
                        frontEndEngineAbstraction = new FrontEndEngineImplementation(
                            loggingContext,
                            frontEndContext.PathTable,
                            config,
                            mutableCommandlineConfig.Startup,
                            mountsTable,
                            InputTracker.CreateDisabledTracker(loggingContext),
                            null,
                            null,
                            () => FileContentTable.CreateStub(),
                            5000,
                            false);

                        pipGraphBuilder = new PipGraph.Builder(
                            EngineSchedule.CreateEmptyPipTable(engineContext),
                            engineContext,
                            Scheduler.Tracing.Logger.Log,
                            loggingContext,
                            config,
                            mountsTable.MountPathExpander,
                            fingerprintSalt: config.Cache.CacheSalt,
                            directoryMembershipFingerprinterRules: new DirectoryMembershipFingerprinterRuleSet(config, engineContext.StringTable));

                        if (!AddConfigurationMountsAndCompleteInitialization(config, loggingContext, mountsTable))
                        {
                            return(false);
                        }

                        IDictionary <ModuleId, MountsTable> moduleMountsTableMap;
                        if (!mountsTable.PopulateModuleMounts(config.ModulePolicies.Values, out moduleMountsTableMap))
                        {
                            Contract.Assume(loggingContext.ErrorWasLogged, "An error should have been logged after MountTable.PopulateModuleMounts()");
                            return(false);
                        }
                    }
                    else
                    {
                        frontEndEngineAbstraction = new BasicFrontEndEngineAbstraction(frontEndContext.PathTable, frontEndContext.FileSystem, config);
                    }
                }

                using (frontEndEngineAbstraction is IDisposable ? (IDisposable)frontEndEngineAbstraction : null)
                {
                    // Attempt to build and/or analyze the workspace
                    if (!controller.PopulateGraph(
                            cache: cache,
                            graph: pipGraphBuilder,
                            engineAbstraction: frontEndEngineAbstraction,
                            evaluationFilter: evaluationFilter,
                            configuration: config,
                            startupConfiguration: mutableCommandlineConfig.Startup))
                    {
                        workspace = frontEndHostController.GetWorkspace();

                        // Error has been reported already
                        return(false);
                    }

                    pipGraph = pipGraphBuilder;
                }
            }

            Contract.Assert(frontEndHostController != null);

            workspace = frontEndHostController.GetWorkspace();

            if (mutableCommandlineConfig.Engine.Phase == EnginePhases.AnalyzeWorkspace)
            {
                // If workspace construction is successful, we run the linter on all specs.
                // This makes sure the workspace will carry all the errors that will occur when running the same specs in the regular engine path
                workspace = CreateLintedWorkspace(
                    workspace,
                    frontEndContext.LoggingContext,
                    config.FrontEnd,
                    pathTable);
            }

            return(true);
        }
示例#53
0
        public static async Task AnimateLights(EngineContext engineContext)
        {
            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                if (engineContext.InputManager.IsKeyPressed(Keys.F3))
                {
                    var lights = engineContext.EntityManager.Entities.Components(LightComponent.Key);
                    await engineContext.Scheduler.WhenAll(lights.Select((lightComponent, index) =>
                        engineContext.Scheduler.Add(() => AnimateLight(engineContext, index, lightComponent))).ToArray());
                }
            }
        }
示例#54
0
        private void MoveEntity(EngineContext engineContext, Entity entity, GizmoAction currentGizmoAction, Vector3 pickingGizmoOrigin, Vector3 pickingObjectOrigin, Vector2 delta)
        {
            var renderingSetup = RenderingSetup.Singleton;

            // Get current transformation component
            var transformationComponent = entity != null ? entity.Transformation : null;

            if (delta == Vector2.Zero || transformationComponent == null)
            {
                return;
            }

            var transformationComponentValues = transformationComponent.Value as TransformationTRS;

            if (transformationComponentValues == null)
            {
                return;
            }

            var viewParameters = renderingSetup.MainPlugin.ViewParameters;

            transformationComponentValues.Translation = pickingObjectOrigin;

            if ((currentGizmoAction & GizmoAction.Translation) != GizmoAction.None)
            {
                var axes      = new Vector3[3];
                int axisCount = 0;
                if ((currentGizmoAction & GizmoAction.TranslationX) != GizmoAction.None)
                {
                    axes[axisCount++] = Vector3.UnitX;
                }
                if ((currentGizmoAction & GizmoAction.TranslationY) != GizmoAction.None)
                {
                    axes[axisCount++] = Vector3.UnitY;
                }
                if ((currentGizmoAction & GizmoAction.TranslationZ) != GizmoAction.None)
                {
                    axes[axisCount++] = Vector3.UnitZ;
                }

                if (axisCount == 3)
                {
                    throw new NotImplementedException("Translation should only act on two axes.");
                }

                var viewProj = viewParameters.Get(TransformationKeys.View) * viewParameters.Get(TransformationKeys.Projection);

                // Only one axis, we should find the best second "helper" axis to build our plan.
                // Currently, it looks for another unit axis to build that plan (the one that is the most "perpendicular" to current axis in screenspace).
                if (axisCount == 1)
                {
                    Vector3 projectedAxis;
                    Vector3.TransformNormal(ref axes[0], ref viewProj, out projectedAxis);
                    var unitX = Vector3.TransformNormal(Vector3.UnitX, viewProj);
                    var unitY = Vector3.TransformNormal(Vector3.UnitY, viewProj);
                    var unitZ = Vector3.TransformNormal(Vector3.UnitZ, viewProj);

                    // Ignore Z axis (depth)
                    projectedAxis.Z = 0.0f;
                    unitX.Z         = 0.0f;
                    unitY.Z         = 0.0f;
                    unitZ.Z         = 0.0f;

                    // Normalize
                    projectedAxis.Normalize();
                    unitX.Normalize();
                    unitY.Normalize();
                    unitZ.Normalize();

                    var dotX = Math.Abs(Vector3.Dot(unitX, projectedAxis));
                    var dotY = Math.Abs(Vector3.Dot(unitY, projectedAxis));
                    var dotZ = Math.Abs(Vector3.Dot(unitZ, projectedAxis));

                    if (dotX < dotY && dotX < dotZ)
                    {
                        axes[1] = Vector3.UnitX;
                    }
                    else if (dotY < dotZ)
                    {
                        axes[1] = Vector3.UnitY;
                    }
                    else
                    {
                        axes[1] = Vector3.UnitZ;
                    }
                }

                var parentMatrix = transformationComponent.Parent != null ? transformationComponent.Parent.WorldMatrix : Matrix.Identity;
                parentMatrix.Invert();

                transformationComponentValues.Translation += Vector3.TransformNormal(ComputePickingDelta(engineContext, axes[0], axes[1], ref viewProj, pickingGizmoOrigin, pickingObjectOrigin, delta), parentMatrix);
                if (axisCount == 2)
                {
                    transformationComponentValues.Translation += Vector3.TransformNormal(ComputePickingDelta(engineContext, axes[1], axes[0], ref viewProj, pickingGizmoOrigin, pickingObjectOrigin, delta), parentMatrix);
                }
            }
        }
示例#55
0
        //[XenkoScript]
        public static async Task<Entity> LoadDragon(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;
            renderingSetup.RegisterLighting(engineContext);
            
            var characterEntity = await AnimScript.LoadFBXModel(engineContext, "/global_data/gdc_demo/char/dragon_camera.hotei#");
            characterEntity.Name = "Dragon";
            Scheduler.Current.Add(() => AnimScript.AnimateFBXModel(engineContext, characterEntity, CaveSceneTotalTime, CaveSceneRestart));

            // Setup predefined specular intensities/power for dragon
            foreach (var entity in ParameterContainerExtensions.CollectEntityTree(characterEntity))
            {
                var meshComponent = entity.Get(ModelComponent.Key);
                if (meshComponent == null)
                    continue;

                foreach (var effectMesh in meshComponent.InstantiatedSubMeshes)
                {
                    effectMesh.Value.Parameters.Set(TessellationKeys.DesiredTriangleSize, 4.0f);

                    switch (effectMesh.Key.EffectData.Part)
                    {
                        case "skin":
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.4f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.4f);
                            break;
                        case "mouth":
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.3f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.3f);
                            break;
                        case "skin2":
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.5f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.5f);
                            break;
                        case "wing":
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.4f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.5f);
                            break;
                        case "tooth":
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.4f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.7f);
                            break;
                        case "eye":
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.7f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.7f);
                            break;
                        default:
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.3f);
                            effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 0.3f);
                            break;
                    }
                }
            }

            return characterEntity;
        }
示例#56
0
        private void RotateEntity(EngineContext engineContext, Entity entity, GizmoAction currentGizmoAction, Vector2 delta)
        {
            // Get current transformation component
            var transformationComponent = entity != null ? entity.Transformation : null;

            //transformationComponent.Rotation = pickingObjectRotation;

            if (delta == Vector2.Zero || transformationComponent == null)
            {
                return;
            }

            var transformationComponentValues = transformationComponent.Value as TransformationTRS;

            if (transformationComponentValues == null)
            {
                return;
            }

            Matrix currentRotationMatrix;

            Vector3 pickingGizmoRotationLocal;

            transformationComponentValues.LocalMatrix.DecomposeXYZ(out pickingGizmoRotationLocal);

            var currentRotationMatrixLocal = Matrix.RotationX(pickingGizmoRotationLocal.X)
                                             * Matrix.RotationY(pickingGizmoRotationLocal.Y)
                                             * Matrix.RotationZ(pickingGizmoRotationLocal.Z);

            var parentMatrix        = transformationComponent.Parent != null ? transformationComponent.Parent.WorldMatrix : Matrix.Identity;
            var parentMatrixInverse = Matrix.Invert(parentMatrix);

            float deltaRotation = (delta.X + delta.Y) * 0.01f;

            Vector3 rotationBefore;

            currentRotationMatrixLocal.DecomposeXYZ(out rotationBefore);

            // Apply the rotation in parent local space
            if (currentGizmoAction == GizmoAction.RotationX)
            {
                currentRotationMatrix = currentRotationMatrixLocal * parentMatrixInverse * Matrix.RotationX(deltaRotation) * parentMatrix;
            }
            else if (currentGizmoAction == GizmoAction.RotationY)
            {
                currentRotationMatrix = currentRotationMatrixLocal * parentMatrixInverse * Matrix.RotationY(deltaRotation) * parentMatrix;
            }
            else if (currentGizmoAction == GizmoAction.RotationZ)
            {
                currentRotationMatrix = currentRotationMatrixLocal * parentMatrixInverse * Matrix.RotationZ(deltaRotation) * parentMatrix;
            }
            else
            {
                throw new NotImplementedException();
            }

            Vector3 rotationAfter;

            currentRotationMatrix.DecomposeXYZ(out rotationAfter);

            transformationComponentValues.RotationEuler += rotationAfter - rotationBefore;
        }
示例#57
0
        public static async Task Run(EngineContext engineContext)
        {
            var renderingSetup = RenderingSetup.Singleton;
            renderingSetup.RegisterLighting(engineContext);

            ParticlePlugin particlePlugin;
            if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("ParticlePlugin", out particlePlugin))
            {
                ScriptParticleSmoke.Run(engineContext);
            }


            var yebisPlugin = engineContext.RenderContext.RenderPassPlugins.OfType<YebisPlugin>().FirstOrDefault();
            if (yebisPlugin != null)
            {
                var yebisConfig = AppConfig.GetConfiguration<YebisConfig>("Yebis");

                // yebisPlugin.ToneMap.Type = ToneMapType.Linear;
                yebisPlugin.ToneMap.Gamma = yebisConfig.Gamma;
                yebisPlugin.ColorCorrection.Saturation = yebisConfig.Saturation;
                yebisPlugin.ColorCorrection.Contrast = yebisConfig.Contrast;
                yebisPlugin.ColorCorrection.Brightness = yebisConfig.Brightness;
                yebisPlugin.ColorCorrection.ColorTemperature = yebisConfig.ColorTemperature;
                yebisPlugin.Lens.Vignette.Enable = true;
                yebisPlugin.Lens.Vignette.PowerOfCosine = 5.0f;
                yebisPlugin.Lens.Distortion.Enable = true;
                yebisPlugin.Lens.Distortion.EdgeRoundness = 0.1f;
                yebisPlugin.Lens.Distortion.EdgeSmoothness = 1.0f;
            }
            
            // Run the script to animate the intro fade-in/fade-out
            engineContext.Scheduler.Add(async () => await AnimateIntroAndEndScene(engineContext));

            var cameraEntityRootPrefab = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/char/camera.hotei#");
            var lightCamEntityRootPrefab = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/char/light_cam.hotei#");

            var lightCamEntityRoot = Prefab.Inherit(lightCamEntityRootPrefab);
            var cameraEntityRoot = Prefab.Inherit(cameraEntityRootPrefab);

            engineContext.EntityManager.AddEntity(cameraEntityRoot);
            engineContext.EntityManager.AddEntity(lightCamEntityRoot);
            Scheduler.Current.Add(() => AnimScript.AnimateFBXModel(engineContext, cameraEntityRoot, CaveSceneTotalTime, CaveSceneRestart));
            Scheduler.Current.Add(() => AnimScript.AnimateFBXModel(engineContext, lightCamEntityRoot, CaveSceneTotalTime, CaveSceneRestart));

            foreach(var light in ParameterContainerExtensions.CollectEntityTree(lightCamEntityRoot))
            {
                var lightComp = light.Get(LightComponent.Key);
                if (lightComp != null)
                {
                    
                    if (!lightComp.ShadowMap && lightComp.Type == LightType.Directional)
                    {
                        lightComp.Intensity *= 0.1f;
                    }
                }
            }

            var config = AppConfig.GetConfiguration<Script1.Config>("Script1");

            var shadowMap1 = new Entity();
            var shadowMap2 = new Entity();
            shadowMap1.Set(TransformationComponent.Key, TransformationTRS.CreateComponent());
            shadowMap2.Set(TransformationComponent.Key, TransformationTRS.CreateComponent());
            shadowMap1.Set(LightComponent.Key, new LightComponent { Type = LightType.Directional, Intensity = 0.9f, Color = new Color3(0.9f, 0.9f, 1.0f), LightDirection = new Vector3(-0.2f, -0.1f, -1.0f), ShadowMap = true, DecayStart = 40000.0f });
            shadowMap2.Set(LightComponent.Key, new LightComponent { Type = LightType.Directional, Color = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(-0.5f, 0.1f, -1.0f), ShadowMap = true, DecayStart = 40000.0f });
            shadowMap1.Set(LightShaftsComponent.Key, new LightShaftsComponent { Color = new Color3(1.0f, 1.0f, 1.0f), LightShaftsBoundingBoxes =
                {
                    new EffectMeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollection { { TransformationKeys.World, Matrix.Scaling(3000, 3500, 3000) * Matrix.Translation(-2500, 0, 1500) } } }
                } });
            shadowMap2.Set(LightShaftsComponent.Key, new LightShaftsComponent { Color = new Color3(1.0f, 1.0f, 1.0f), LightShaftsBoundingBoxes =
                {
                    new EffectMeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollection { { TransformationKeys.World, Matrix.Scaling(3500, 3500, 3000) * Matrix.Translation(-3000, 0, 1500) } } }
                } });

            engineContext.EntityManager.AddEntity(shadowMap1);
            engineContext.EntityManager.AddEntity(shadowMap2);


            var dragon = await LoadDragon(engineContext);
            await LoadCave(engineContext, dragon);

            var dragonHead = engineContext.EntityManager.Entities.FirstOrDefault(x => x.Name == "English DragonHead");
            TransformationTRS headCameraTransfo = null;
            if (dragonHead != null)
            {
                var headCamera = new Entity("Head camera");
                headCamera.Set(CameraComponent.Key, new CameraComponent { AspectRatio = 16.0f / 9.0f, VerticalFieldOfView = (float)Math.PI * 0.3f, Target = dragonHead, AutoFocus = true, NearPlane = 10.0f });
                headCamera.Set(TransformationComponent.Key, new TransformationComponent(new TransformationTRS { Translation = new Vector3(100.0f, -100.0f, 300.0f) }));
                //engineContext.EntitySystem.Entities.Add(headCamera);
                dragonHead.Transformation.Children.Add(headCamera.Transformation);
            }

            engineContext.Scheduler.Add(() => AnimateLights(engineContext));

            // Performs several full GC after the scene has been loaded
            for (int i = 0; i < 10; i++)
            {
                GC.Collect();
                Thread.Sleep(1);
            }

            while (true)
            {
                await engineContext.Scheduler.NextFrame();

                if (headCameraTransfo != null)
                {
                    var time = (double)DateTime.UtcNow.Ticks / (double)TimeSpan.TicksPerSecond;
                    float rotationSpeed = 0.317f;
                    var position = new Vector2((float)Math.Cos(time * rotationSpeed), (float)Math.Sin(time * rotationSpeed)) * 330.0f * ((float)Math.Sin(time * 0.23f) * 0.4f + 0.9f);
                    headCameraTransfo.Translation = new Vector3(position.X, -150.0f + (float)Math.Cos(time * rotationSpeed) * 50.0f, position.Y);
                }

                if (engineContext.InputManager.IsKeyPressed(Keys.F1))
                {
                    bool isWireframeEnabled = renderingSetup.ToggleWireframe();
                    if (yebisPlugin != null)
                    {
                        yebisPlugin.DepthOfField.Enable = !isWireframeEnabled;
                        yebisPlugin.Lens.Vignette.Enable = !isWireframeEnabled;
                        yebisPlugin.Lens.Distortion.Enable = !isWireframeEnabled;
                    }
                }

                if (engineContext.InputManager.IsKeyPressed(Keys.D1))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(0);
                if (engineContext.InputManager.IsKeyPressed(Keys.D2))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(10);
                if (engineContext.InputManager.IsKeyPressed(Keys.D3))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(20);
                if (engineContext.InputManager.IsKeyPressed(Keys.D4))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(30);
                if (engineContext.InputManager.IsKeyPressed(Keys.D5))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(40);
                if (engineContext.InputManager.IsKeyPressed(Keys.D6))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(50);
                if (engineContext.InputManager.IsKeyPressed(Keys.D7))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(60);
                if (engineContext.InputManager.IsKeyPressed(Keys.D8))
                    engineContext.CurrentTime = TimeSpan.FromSeconds(70);

                if (engineContext.InputManager.IsKeyPressed(Keys.T))
                {
                    if (particlePlugin != null)
                    {
                        particlePlugin.EnableSorting = !particlePlugin.EnableSorting;
                    }
                }

            }
        }
示例#58
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info()
                {
                    Title = "Swagger Test UI", Version = "v1"
                });
                options.CustomSchemaIds(type => type.FullName);                                                 // 解决相同类名会报错的问题
                options.IncludeXmlComments(Path.Combine(Directory.GetCurrentDirectory(), "Weixin.WebApi.xml")); // 标注要使用的 XML 文档
                                                                                                                //启用auth支持
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
            });

            services.AddHttpClient("wexin", c => { })
            .ConfigurePrimaryHttpMessageHandler(messageHandler =>
            {
                var handler = new HttpClientHandler();
                if (handler.SupportsAutomaticDecompression)
                {
                    handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                }
                return(handler);
            });

            services.Configure <WeixinSetting>(Configuration.GetSection("WeiXin"));


            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IService)))).ToList();

            types.ForEach(type =>
            {
                services.AddSingleton(type);
            });
            services.AddScoped(typeof(IAuthService), typeof(CookieAuthenticationService));
            services.Register(Configuration);
            services.AddCors();

            //初始化MyOwnModel实例并且映射appSettings里的配置
            services.AddOptions();
            services.Configure <MyOwnModel>(Configuration.GetSection("MyOwn"));
            //通过name注入不同options服务
            services.Configure <MyOwnModel>("自定义配置", model =>
            {
                model.Age  = 1;
                model.Name = "dsdf";
            });
            services.AddDistributedRedisCache(r =>
            {
                r.Configuration = Configuration["Redis:ConnectionString"];
            });
            services.AddHttpClient();
            services.AddSession();
            //Configuration.GetSection("").
            services.Configure <JwtOption>(Configuration.GetSection("JwtOption"));

            EngineContext.Create(services.BuildServiceProvider());
        }
 // TODO: Remove if not needed
 /*public MockGameEnvironment () : base(new MockEngineContext())
 {
 }*/
 public MockGameEnvironment(EngineContext context)
     : base(context)
 {
 }
 public EngineContext(ImportEngine importEngine, EngineContext parentEngineContext)
 {
     _importEngine        = importEngine;
     _parentEngineContext = parentEngineContext;
 }