private void LoadGame()
        {
            var viweportSize  = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
            var scaleviweport = (viweportSize / _aspect);
            var grid          = new Grid(_spriteBatch, new Size(8, 8));

            grid.Position       = scaleviweport * 0.5f;
            grid.EventFinished += OnGameFinished; //Event to gameover
            _root.AddChild(grid);
        }
Beispiel #2
0
        private RootNode TestCase(AIMember aiMember)
        {
            RootNode root = new RootNode();

            root
            .AddChild(new Selector()
                      .AddChild(new Condition(() => _timer > 3 && aiMember.Index < 1)
                                .AddChild(new Sequeter()
                                          .AddChild(new PrintAction("[1]State In"))
                                          .AddChild(new SetValAction(() => aiMember.Index = 1))
                                          .AddChild(new DelayAction(5f))
                                          .AddChild(new PrintAction("[1]State Out"))))
                      .AddChild(new Condition(() => _timer > 10 && aiMember.Index < 2)
                                .AddChild(new Sequeter()
                                          .AddChild(new PrintAction("[2]State In"))
                                          .AddChild(new SetValAction(() => aiMember.Index = 2))
                                          .AddChild(new DelayAction(5f))
                                          .AddChild(new PrintAction("[2]State Out"))))
                      .AddChild(new Condition(() => _timer > 20f)
                                .AddChild(new Sequeter()
                                          .AddChild(new SetValAction(() => _timer         = 0))
                                          .AddChild(new SetValAction(() => aiMember.Index = 0))))
                      .AddChild(new PrintAction("[3] Default Case")));

            return(root);
        }
Beispiel #3
0
        public void Node_ShouldAddChildren()
        {
            // Arrange
            Node root   = new RootNode();
            Node child1 = Argument("foo", new IntegerArgument(), true, null);
            Node child2 = Argument("bar", new IntegerArgument(), true, null);
            Node child3 = Argument("baz", new IntegerArgument(), true, null);

            // Act
            root.AddChild(child1);
            root.AddChild(child2);
            root.AddChild(child3);

            // Assert
            Assert.AreEqual(root.Children.Count, 3);
        }
        /// <summary>
        /// Handles changes to the references items in the project and updates the project tree.
        /// </summary>
        /// <param name="e">A description of the changes made to the project.</param>
        private void ProjectSubscriptionService_Changed(IProjectVersionedValue <
                                                            Tuple <IProjectSubscriptionUpdate,
                                                                   IProjectCatalogSnapshot,
                                                                   IProjectSharedFoldersSnapshot> > e)
        {
            DependenciesChange dependenciesChange;

            lock (_rootNodeSync)
            {
                dependenciesChange = ProcessDependenciesChanges(e.Value.Item1, e.Value.Item2);

                // process separatelly shared projects changes
                ProcessSharedProjectImportNodes(e.Value.Item3, dependenciesChange);

                // Apply dependencies changes to actual RootNode children collection
                // remove first nodes from actual RootNode
                dependenciesChange.RemovedNodes.ForEach(RootNode.RemoveChild);

                ProcessDuplicatedNodes(dependenciesChange);

                dependenciesChange.UpdatedNodes.ForEach((topLevelNode) =>
                {
                    var oldNode = RootNode.Children.FirstOrDefault(x => x.Id.Equals(topLevelNode.Id));
                    if (oldNode != null)
                    {
                        RootNode.RemoveChild(oldNode);
                        RootNode.AddChild(topLevelNode);
                    }
                });

                dependenciesChange.AddedNodes.ForEach(RootNode.AddChild);
            }

            OnDependenciesChanged(dependenciesChange.GetDiff(), e);
        }
Beispiel #5
0
        protected override void LoadContent()
        {
            Window.Title = "Thick Wireframes";
            Mesh teapot = new Teapot("Utah Teapot");

            teapot.SetScale(30f);
            teapot.Translation = new Vector3(0, -50, 0);
            teapot.Material    = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            teapot.Material.SetRenderState(RasterizerState.CullNone);

            Mesh wireframe = CreateWireframeData("Utah Wireframe", teapot.MeshData);

            wireframe.RenderBucketType = RenderBucketType.PostBucket;
            wireframe.Transform.Set(teapot.Transform);

            Material wireMat = new Material("WireMaterial");

            wireMat.LoadEffect(ContentManager.Load <Effect>("Shaders//WireframeEffect.fx").Clone());
            wireMat.SetEngineParameter("WVP", EngineValue.WorldViewProjection);
            wireMat.SetParameter("WinScale", new Vector2(Renderer.CurrentCamera.Viewport.Width / 2, Renderer.CurrentCamera.Viewport.Height / 2));
            wireMat.SetParameter("WireColor", new Vector3(.8f, .1f, .1f));
            wireMat.SetParameter("FillColor", new Vector4(.7f, .8f, .9f, .5f));
            wireMat.SetRenderState(BlendState.AlphaBlendNonPremultiplied);
            wireMat.SetRenderState(RasterizerState.CullNone);
            wireframe.SetMaterial(wireMat);

            RootNode.AddChild(teapot);
            RootNode.AddChild(wireframe);

            RootNode.AddController(new RotateController(Vector3.Up, 25));
        }
Beispiel #6
0
        protected override void LoadContent()
        {
            Window.Title = "Render Target Sample";

            //Create the box we'll render off screen
            _offscreenCube          = new Box("Offscreen box", 10, 10, 10);
            _offscreenCube.Material = ContentManager.Load <Material>("LitBasicTexture.tem");
            _offscreenCube.Material.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//rock_diff.dds"));
            _offscreenCube.AddController(new RotateController(Vector3.Normalize(Vector3.Add(Vector3.Up, Vector3.Right)), 45.0f));

            PointLight pl = new PointLight();

            pl.Diffuse  = Color.CornflowerBlue;
            pl.Position = new Vector3(0, 25, 25);
            pl.Ambient  = Color.LightBlue;
            _offscreenCube.AddLight(pl);
            _offscreenCube.SceneHints.LightCombineHint = LightCombineHint.Local;
            _offscreenCube.RenderBucketType            = RenderBucketType.Skip;

            //Create a render target that also has a depth stencil.
            _renderTarget = new RenderTarget2D(512, 512, true, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);

            //Camera we'll use for the off screen rendering
            _targetCamera          = new Camera(new Viewport(0, 0, 512, 512));
            _targetCamera.Position = new Vector3(0, 0, 50);
            _targetCamera.SetProjection(45.0f, 0.1f, 5000.0f);
            _targetCamera.Update();

            //Create a box that we'll attach to the scene graph and render as normal.
            _box          = new Box("OnScreen box", 50, 50, 50);
            _box.Material = ContentManager.Load <Material>("BasicTexture.tem");
            //Since render target is a texture, we can set it to the material's effect.
            _box.Material.SetParameter("DiffuseMap", _renderTarget);
            RootNode.AddChild(_box);
        }
Beispiel #7
0
        public void TestNodeParent()
        {
            var root  = new RootNode("Root");
            var trunk = new TrunkNode("Trunk");

            root.AddChild(trunk);

            Assert.AreEqual(root, trunk.GetParent());
        }
Beispiel #8
0
        public void Node_ShouldGetArgumentChildren_AsRelevantNodes()
        {
            // Arrange
            RootNode root   = new RootNode();
            Node     child1 = Literal("foo", true, null);
            Node     child2 = Literal("bar", true, null);
            Node     child3 = Argument("baz", new IntegerArgument(), true, null);
            Node     child4 = Argument("qux", new BooleanArgument(), true, null);

            root.AddChild(child1);
            root.AddChild(child2);
            root.AddChild(child3);
            root.AddChild(child4);
            IStringReader reader = new StringReader("123");

            // Act
            List <Node> relevantNodes = new List <Node>(root.GetRelevantNodes(reader));

            // Assert
            Assert.AreEqual(relevantNodes.Count, 2);
        }
Beispiel #9
0
        protected override void Context()
        {
            _repository1 = A.Fake <DataRepository>();
            _repository2 = A.Fake <DataRepository>();
            var rootNode           = new RootNode(new RootNodeType("ObservedDataFolder", ApplicationIcons.ObservedDataFolder, ClassificationType.ObservedData));
            var classificationNode = new ClassificationNode(new Classification());

            classificationNode.AddChild(new ObservedDataNode(new ClassifiableObservedData {
                Subject = _repository1
            }));
            rootNode.AddChild(classificationNode);
            rootNode.AddChild(new ObservedDataNode(new ClassifiableObservedData {
                Subject = _repository2
            }));
            _data = new DragDropInfo(
                new List <ITreeNode>
            {
                rootNode
            });
            base.Context();
        }
Beispiel #10
0
        protected override void LoadContent()
        {
            Window.Title = "Spatial Controller Sample";

            //Create a box with a simple color material
            Box box = new Box("MyBox", 20, 20, 20);

            box.Material = ContentManager.Load <Material>("LitBasicColor.tem");
            box.Material.SetParameter("MatDiffuse", Color.Crimson.ToVector3());
            //Set the custom controller to the box, this will get updated everytime the scene graph is updated.
            box.AddController(new RotateScaleController(.5f, new Vector2(.2f, 3), 45, Vector3.Up));
            RootNode.AddChild(box);
        }
Beispiel #11
0
        protected override void LoadContent()
        {
            ModelLoaderParameters mlp = new ModelLoaderParameters();

            mlp.SwapWindingOrder = true;
            mlp.NormalGeneration = NormalGeneration.Face;

            mlp.PreferLitMaterials   = true;
            mlp.GenerateTangentBasis = false;
            ship = ContentManager.Load <Spatial>("Models\\station.dxs", mlp);

            ship.AddController(new Tesla.Scene.Extension.RotateController(new Vector3(0, 1, 0), 5));
            ship.SetRenderState(SamplerState.AnisotropicWrap);
            engineMat = ContentManager.Load <Material>("BasicTexture.tem");

            Material mat = new Material();

            mat.LoadEffect(ContentManager.Load <Effect>("Shaders//TextureGlowEffect.fx"));
            mat.SetActiveTechnique("TextureGlow");
            mat.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//station_diff.dds"));
            mat.SetParameter("EmissiveMap", ContentManager.Load <Texture2D>("Textures//station_glow.dds"));
            mat.SetParameter("MatEmissive", new Vector3(.5f, .5f, .5f));
            mat.SetEngineParameter("WVP", Tesla.Core.EngineValue.WorldViewProjection);
            mat.SetEngineParameter("World", Tesla.Core.EngineValue.WorldMatrix);
            mat.SetEngineParameter("WorldIT", Tesla.Core.EngineValue.WorldInverseTranspose);
            mat.SetEngineParameter("EyePos", Tesla.Core.EngineValue.CameraPosition);

            ship.SetMaterial(mat);

            engineMat.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//station_glow.dds"));

            width  = Renderer.CurrentCamera.Viewport.Width;
            height = Renderer.CurrentCamera.Viewport.Height;

            bool test = Renderer.Adapter.QueryRenderTargetFormat(SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 4);

            sceneRT    = new RenderTarget2D(width, height, false, Window.SwapChain.PresentationParameters.BackBufferFormat, Window.SwapChain.PresentationParameters.DepthStencilFormat, Window.SwapChain.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents);
            rt1        = new RenderTarget2D(width, height, true, sceneRT.Format, DepthFormat.None);
            rt2        = new RenderTarget2D(width, height, true, sceneRT.Format, DepthFormat.None);
            rt3        = new RenderTarget2D(width, height, true, sceneRT.Format, DepthFormat.None);
            blurEffect = ContentManager.Load <Effect>("Shaders//GaussianBlur.fx");
            batch      = new SpriteBatch();

            RootNode.AddChild(ship);
            sky = new Box("Space", Vector3.Zero, 100, 100, 100);
            sky.SceneHints.RenderBucketType = RenderBucketType.Skip;
            sky.Material = ContentManager.Load <Material>("Materials//SpaceSkybox.tem");

            RootNode.SetModelBound(new Tesla.Bounding.BoundingBox());
        }
Beispiel #12
0
        private void CreatePicks(PickQuery query)
        {
            if (query.Count == 0)
            {
                return;
            }
            query.Sort();

            //Lazily create the mesh that holds the pick visuals, for this example we're only doing the closest picked
            //triangle
            if (picks == null)
            {
                picks          = new Mesh("Picks");
                picks.Material = ContentManager.Load <Material>("Materials//BasicColor.tem").Clone();
                picks.Material.SetParameter("DiffuseColor", Color.Yellow);
                picks.SetRenderState(RasterizerState.CullNoneWireframe);
                picks.SetRenderState(DepthStencilState.None);
                picks.MeshData.Positions            = new DataBuffer <Vector3>(3);
                picks.MeshData.UseIndexedPrimitives = false;
                picks.MeshData.Reconstruct();
                picks.SceneHints.RenderBucketType = RenderBucketType.PostBucket;
                picks.SceneHints.PickingHint      = PickingHint.None;
                RootNode.AddChild(picks);

                pickRay          = new Line("PickRay");
                pickRay.Material = ContentManager.Load <Material>("Materials//BasicVertColor.tem").Clone();
                RootNode.AddChild(pickRay);
            }

            DataBuffer <Vector3> db = picks.MeshData.Positions;

            db.Position = 0;
            PickResult results = query.ClosestPick.Value;
            Ray        ray     = results.SourceRay;

            //Get the closest primitive intersection record, and the closest intersection triangle (a ray may pass through many
            //triangles, we want the one closest to the ray's origin). These should exist, if we have results.
            IntersectionRecord record = results.PrimitiveIntersectionRecord.Value.ClosestIntersection.Value;
            Triangle           tri    = record.Triangle.Value;

            db.Set(tri.PointA);
            db.Set(tri.PointB);
            db.Set(tri.PointC);

            //Set the pick ray so we can see it on the screen
            pickRay.SetLine(ray.Origin, ray.Origin + ray.Direction * (record.Distance + 100), Color.Orange, Color.Orange);

            //Update the pick result with the triangle data
            picks.MeshData.UpdateVertexData <Vector3>(VertexSemantic.Position, db);
        }
Beispiel #13
0
        void RecieveCode(IAsyncResult rs)
        {
            HttpListenerContext ls = listener.EndGetContext(rs);

            HttpListenerRequest request = ls.Request;
            string cloudname            = request.QueryString.Get("cloudname");
            string id    = request.QueryString.Get("id");
            string path  = request.QueryString.Get("path");
            string email = request.QueryString.Get("email");
            string range = request.Headers.Get("Range");

            CloudType type = CloudType.Folder;
            Stream    stream;
            long      start_range = -1;
            long      end_range   = -1;
            IItemNode filenode    = null;

            if (range != null)
            {
                string[] range_arr = range.Split('-');
                long.TryParse(range_arr[0], out start_range);
                long.TryParse(range_arr[1], out end_range);
            }

            if (cloudname != null && id != null && Enum.TryParse <CloudType>(cloudname, out type) && type != CloudType.LocalDisk && type != CloudType.Folder)
            {
                if (email == null)
                {
                    email = AppSetting.settings.GetDefaultCloud(type);
                }
                RootNode rootnode = AppSetting.settings.GetCloudRootNode(email, type);
                filenode = new ItemNode(new NodeInfo()
                {
                    ID = id
                });
                rootnode.AddChild(filenode);
            }
            else if (path != null && File.Exists(path))
            {
                type     = CloudType.LocalDisk;
                filenode = ItemNode.GetNodeFromDiskPath(path);
            }
            else//return 404 not found
            {
            }

            stream = AppSetting.ManageCloud.GetFileStream(filenode, start_range, end_range, false);//mega need cal chunk and size file

            HttpListenerResponse response = ls.Response;
        }
Beispiel #14
0
        protected override void LoadContent()
        {
            Window.Title = "Ray Picking Sample";
            //Load a model that we'll use to pick
            ModelLoaderParameters mlp = new ModelLoaderParameters();

            mlp.SwapWindingOrder   = true;
            mlp.NormalGeneration   = NormalGeneration.Crease;
            mlp.PreferLitMaterials = true;

            Spatial jeep = ContentManager.Load <Spatial>("Models//Jeep.dxs", mlp);

            //jeep.Translation = new Vector3(0, -50, 0);
            jeep.Rotation = Quaternion.FromAngleAxis(MathHelper.ToRadians(140), Vector3.UnitY);
            jeep.SetModelBound(new BoundingBox());
            RootNode.AddChild(jeep);

            //Adjust the default camera a tad
            Renderer.CurrentCamera.Position = new Vector3(0, 100, 100);
            Renderer.CurrentCamera.LookAt(jeep.Translation, Vector3.Up);
            Renderer.CurrentCamera.Update();

            //Set the mouse visible so we can see the cursor
            Window.IsMouseVisible = true;

            //Create our query
            query = new PickQuery();
            //We want to enable primitive picking to get triangle accurate results, when we do the intersection tests,
            //the utility will first do a board bounding volume test, and if that succeeds then a finer primitive test.
            query.EnablePrimitivePicking = true;

            //Setup out input - whenever we left click, we'll cast a ray into the scene
            InputLayer.RegisterTrigger(new InputTrigger(new InputCondition(delegate(GameTime time) {
                MouseState ms = Mouse.GetMouseState();
                if (ms.LeftButton == ButtonState.Pressed)
                {
                    return(true);
                }
                return(false);
            }), new InputAction(delegate(GameTime time) {
                MouseState ms = Mouse.GetMouseState();
                query.Clear();

                //The camera class has easy-built in functionality to quickly create a pick ray where the origin
                //of the ray is on the near-plane of the view frustum
                PickingUtil.FindPick(RootNode, Renderer.CurrentCamera.CreatePickRay(ms.Position), query);
                CreatePicks(query);
            })));
        }
Beispiel #15
0
        public virtual void StopAt(long ticks, string segmentName, bool assertStarted = true, bool stopChildren = false)
        {
            var normalized_name = ProfilingNode.NormalizeNodeName(segmentName);

            if (stopChildren)
            {
                var topmost = VisibleCallstack.First((n) => n.SegmentName == normalized_name);
                if (topmost != null)
                {
                    var children = VisibleCallstack.TakeWhile((n) => n.SegmentName != normalized_name).ToArray();
                    children.Select((n) => { StopAt(ticks, n.SegmentName, true, false); return(n); });
                    StopAt(ticks, segmentName, assertStarted, false);
                }
                else if (assertStarted)
                {
                    throw new InvalidOperationException(string.Format("The given profiling segment {0} is not running anywhere in the callstack; it cannot be stopped.", normalized_name));
                }
            }
            else
            {
                if (callstack.Peek().SegmentName == normalized_name)
                {
                    var n = callstack.Pop();
                    n.StopAt(ticks);
                    if (n.Drop)
                    {
                        return;
                    }
                    if (callstack.Count > 0)
                    {
                        callstack.Peek().AddChild(n);
                    }
                    else if (RootNode.SegmentName == n.SegmentName && !RootNode.HasChildren)
                    {
                        RootNode = n; //Replace the root node on the very first call, *if* the segment name matches.
                    }
                    else
                    {
                        RootNode.AddChild(n);
                    }
                }
                else if (assertStarted)
                {
                    throw new InvalidOperationException(string.Format("The given profiling segment {0} is not running at the top of the callstack; it cannot be stopped.", normalized_name));
                }
            }
        }
Beispiel #16
0
        protected override void LoadContent()
        {
            ClearColor = Color.Black;
            MemoryStream   ms       = new MemoryStream();
            BinaryExporter exporter = new BinaryExporter();
            BinaryLoader   loader   = new BinaryLoader();


            Window.Title = "Normal Mapping Sample";
            ModelLoaderParameters mlp = new ModelLoaderParameters();

            mlp.SwapWindingOrder     = true;
            mlp.PreferLitMaterials   = false;
            mlp.GenerateTangentBasis = true;
            mlp.NormalGeneration     = NormalGeneration.Crease;


            Spatial model = ContentManager.Load <Spatial>("Models//starship.dxs", mlp);

            model.SetScale(.15f);
            //model.Material = ContentManager.Load<Material>("NormalMap.tem");
            // model.Material.SetParameter("DiffuseMap", ContentManager.Load<Texture2D>("Textures//rock_diff.dds"));
            //  model.Material.SetParameter("NormalMap", ContentManager.Load<Texture2D>("Textures//rock_norm.dds"));
            // model.Material.SetParameter("MatSpecular", Color.Gray.ToVector3());
            //   model.AddController(new RotateController(new Vector3(.5f, .5f, 0), 25f));
            //model.ComputeTangentBasis();
            // RootNode.AddChild(model);
            RootNode.SetModelBound(new Tesla.Bounding.BoundingBox());

            model = ContentManager.Load <Spatial>("Models//statue.tebo");
            Material mat = ContentManager.Load <Material>("NormalMap.tem").Clone();

            mat.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//statue_diff.dds"));
            mat.SetParameter("NormalMap", ContentManager.Load <Texture2D>("Textures//statue_norm.dds"));
            mat.SetParameter("MatSpecular", new Vector3(.3f, .3f, .3f));
            model.SetMaterial(mat);
            model.Rotation = Quaternion.FromAngleAxis(MathHelper.ToRadians(-90), Vector3.Up);
            model.SetModelBound(new Tesla.Bounding.BoundingBox());
            RootNode.AddChild(model);

            /*
             * model = ContentManager.Load<Spatial>("Models//statue.dxs", mlp);
             * model.Rotation = Quaternion.FromAngleAxis(MathHelper.ToRadians(-90), Vector3.Up);
             * FileStream fs = File.OpenWrite("C:\\Users\\Nicholas Woodfield\\Desktop\\D3D10\\statue2.tebo");
             * exporter.Save(model, fs);
             * fs.Close();*/
        }
Beispiel #17
0
        protected override void LoadContent()
        {
            Window.Title = "DXS Model Loading Sample";
            Renderer.CurrentCamera.Position = new Vector3(-70, 90, 120);
            Renderer.CurrentCamera.LookAt(new Vector3(0, 0, 0), Vector3.Up);
            Renderer.CurrentCamera.Update();

            //When calling ContentManager.Load<T>(), an optional loader parameter can be passed that tells the content importer
            //how to process the content. Model loaders take ModelLoaderParameters and image loaders take ImageLoaderParameters. They
            //can be re-used.
            //
            //In this case, we have to tell the model loader that we want to swap the winding order of polygons so we do not get
            //incorrect rendering. Other options include the angle at which to rotate the model about the XYZ axes, how normals should
            //be generated (if any), if a tangent basis should be generated, where to find textures, or overload material creation by
            //supplying a material to load and use as a template.
            ModelLoaderParameters mlp = new ModelLoaderParameters();

            mlp.SwapWindingOrder   = true;
            mlp.PreferLitMaterials = false;

            //In BasicApp, we registered a DXSModelLoader to the content manager, if we didn't this will throw
            //an exception that we do not have a means to handle the requested content. Loaders are designated by
            //both the runtime type and the content file extension.
            //
            //Notice with loading this model, we use Spatial rather than Mesh, because a model may be in fact a
            //scene graph with multiple parts. We can either have a Node or Mesh returned. In this case,
            //we should have a mesh returned since the model is a single mesh in the file. If the model
            //used two different materials, it would have to be split up into two different meshes
            //and then attached to a Node that would be returned, for example.
            Spatial model = ContentManager.Load <Spatial>("Models//station.dxs", mlp);

            model.AddController(new RotateController(Vector3.Up, 5));
            model.SetModelBound(new BoundingBox());
            RootNode.AddChild(model);

            Box sky = new Box("Space", Vector3.Zero, 100, 100, 100);

            sky.SceneHints.RenderBucketType = RenderBucketType.PreBucket;
            sky.Material = ContentManager.Load <Material>("Materials//SpaceSkybox.tem");

            RootNode.AddChild(sky);
        }
Beispiel #18
0
        protected virtual void ProcessDuplicatedNodes(DependenciesChange dependenciesChange)
        {
            // Now add new nodes and dedupe any nodes that might have same caption.
            // For dedupping we apply aliases to all nodes with similar Caption. Alias
            // is a "Caption (ItemSpec)" and is unique. We try to find existing node with
            // with the same caption, if found we apply alias to both nodes. If not found
            // we also check if there are nodes with alias already applied earlier and having
            // same caption. If yes, we just need to apply alias to our current node only.
            foreach (var nodeToAdd in dependenciesChange.AddedNodes)
            {
                var rootNodeChildren = RootNode.Children;
                var shouldApplyAlias = false;
                var matchingChild    = rootNodeChildren.FirstOrDefault(
                    x => x.Caption.Equals(nodeToAdd.Caption, StringComparison.OrdinalIgnoreCase));
                if (matchingChild == null)
                {
                    shouldApplyAlias = rootNodeChildren.Any(
                        x => x.Caption.Equals(
                            string.Format(CultureInfo.CurrentCulture, "{0} ({1})", nodeToAdd.Caption, x.Id.ItemSpec),
                            StringComparison.OrdinalIgnoreCase));
                }
                else
                {
                    shouldApplyAlias = true;
                }

                if (shouldApplyAlias)
                {
                    if (matchingChild != null)
                    {
                        matchingChild.SetProperties(caption: matchingChild.Alias);
                        dependenciesChange.UpdatedNodes.Add(matchingChild);
                    }

                    nodeToAdd.SetProperties(caption: nodeToAdd.Alias);
                }

                RootNode.AddChild(nodeToAdd);
            }
        }
Beispiel #19
0
        protected override void LoadContent()
        {
            Window.Title = "Many Lights Sample";
            ClearColor   = Color.Black;

            Node lightNode = new Node("LightNode");

            lightNode.SceneHints.LightCombineHint = LightCombineHint.Off;
            for (int i = 0; i < 30; i++)
            {
                CreateRandomLight(i, lightNode);
            }

            RootNode.AddChild(lightNode);

            for (int i = 0; i < 60; i++)
            {
                CreateRandomSphere(i, RootNode);
            }

            RootNode.SetModelBound(new BoundingBox());
        }
Beispiel #20
0
        protected override void LoadContent()
        {
            Window.Title = "Planet Sample";
            Renderer.CurrentCamera.Position = new Vector3(0, 0, 750);

            Sphere planet = new Sphere("Earth", 100, 100, 200);

            planet.Material = ContentManager.Load <Material>("Materials//PlanetMaterial.tem");

            planet.Material.AddLogic(new PlanetLogic());
            planet.Rotation = Quaternion.FromAngleAxis(MathHelper.ToRadians(-90.0f), Vector3.UnitX);
            planet.SceneHints.RenderBucketType = RenderBucketType.Transparent;
            planet.ComputeTangentBasis();
            planet.SetModelBound(new BoundingSphere());
            material = planet.Material;

            Node orbit = new Node("Orbit");

            orbit.AddChild(planet);
            orbit.AddController(new RotateController(Vector3.UnitY, .75f));
            RootNode.AddChild(orbit);
            orbit.Rotation = Quaternion.FromAngleAxis(MathHelper.DegreesToRadians * 45, Vector3.UnitY);

            DirectionalLight dl = new DirectionalLight();

            dl.Direction = new Vector3(-.755f, -.755f, -.755f);
            planet.AddLight(dl);

            //TODO: The planet only renders properly if it's centered at the origin
            //orbit.Translation = new Vector3(0, -500, 0);
            Box sky = new Box("Space", Vector3.Zero, 100, 100, 100);

            sky.SceneHints.RenderBucketType = RenderBucketType.PreBucket;
            sky.Material = ContentManager.Load <Material>("Materials//SpaceSkybox.tem");

            RootNode.AddChild(sky);
        }
Beispiel #21
0
        protected override void LoadContent()
        {
            Window.Title = "Different Lights Sample";
            Type sp = typeof(Spatial);
            Type me = typeof(Mesh);

            bool ishash  = sp.GetHashCode() == sp.GetHashCode();
            bool ishash2 = sp.GetHashCode() == me.GetHashCode();

            bool iseq = sp.Equals(sp);


            pl          = new PointLight();
            pl.Specular = Color.DarkGray; //Cut down on the specular so we don't get blinded

            sl = new SpotLight();
            //Spot light angles - inner angle is where the light is most intense. The intensity smoothly
            //fades from this angle to the outer angle, so we don't have an abrupt cutoff. Essentially spot lights
            //are similar to point lights, except for this restricting cone.
            sl.OuterAngle = 45;
            sl.InnerAngle = 20;
            sl.Direction  = new Vector3(-.577f, -.577f, -.577f);

            //Simple directional light - simulates a light source infinitely away like the Sun.
            dl           = new DirectionalLight();
            dl.Direction = new Vector3(-.577f, -.577f, -.577f);

            activeLight = pl;

            //Create an inverted cube
            Box b = new Box("InsideOut", Vector3.Zero, 100, 100, 100, true);

            b.Material         = ContentManager.Load <Material>("LitBasicColor.tem");
            b.RenderBucketType = RenderBucketType.Skip;

            //These are object material properties (built-in shaders also include Emissive, shininess factor, and an alpha factor)
            b.Material.SetParameter("MatDiffuse", Color.Crimson.ToVector3());
            b.Material.SetParameter("MatAmbient", new Color(.4f, .2f, .2f).ToVector3());
            b.Material.SetParameter("MatSpecular", new Color(.3f, .3f, .3f).ToVector3());
            b.SetModelBound(new BoundingBox());
            RootNode.AddChild(b);

            RootNode.RemoveAllLights();
            RootNode.AddLight(activeLight);
            text = "Active Light: Point";
            //Input response to set the active light
            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.D1, false), new InputAction(
                                                            delegate(GameTime time) {
                activeLight = pl;
                RootNode.RemoveAllLights();
                RootNode.AddLight(activeLight);
                text = "Active Light: Point";
            }
                                                            )));
            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.D2, false), new InputAction(
                                                            delegate(GameTime time) {
                activeLight = sl;
                RootNode.RemoveAllLights();
                RootNode.AddLight(activeLight);
                text = "Active Light: Spot";
            }
                                                            )));
            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.D3, false), new InputAction(
                                                            delegate(GameTime time) {
                activeLight = dl;
                RootNode.RemoveAllLights();
                RootNode.AddLight(activeLight);
                text = "Active Light: Directional";
            }
                                                            )));

            //Set up some text rendering
            batch = new SpriteBatch();
            font  = ContentManager.Load <SpriteFont>("Fonts//comicsans.fnt");
        }
Beispiel #22
0
        protected override void LoadContent()
        {
            Window.Title      = "Render Queue Sample";
            toggleRenderQueue = false;
            toggleTwoPass     = false;

            transpNode = new Node("TransparentNode");
            transpNode.SceneHints.TransparencyType = TransparencyType.OneSided;
            RootNode.AddChild(transpNode);

            orthos   = new Node("OrthoNode");
            orthoCam = new Camera(new Viewport());
            orthoCam.SetFrame(new Vector3(-.5f, -.5f, 0), Matrix.Identity);

            quad1          = new Quad("Quad1", 100, 70);
            quad1.Material = ContentManager.Load <Material>("BasicColor.tem").Clone();
            quad1.Material.SetParameter("DiffuseColor", Color.Blue);
            quad1.Translation         = new Vector3(Window.ClientBounds.Width / 2, Window.ClientBounds.Height / 2, 0);
            quad1.RenderBucketType    = RenderBucketType.Skip;
            quad1.SceneHints.CullHint = CullHint.Never;
            quad1.OrthoOrder          = 5;
            quad1.SetRenderState(DepthStencilState.None);
            quad1.SetRenderState(RasterizerState.CullNone);
            orthos.AddChild(quad1);

            quad2          = new Quad("Quad2", 50, 70);
            quad2.Material = ContentManager.Load <Material>("BasicColor.tem").Clone();
            quad2.Material.SetParameter("DiffuseColor", Color.Red);
            quad2.Translation         = new Vector3(Window.ClientBounds.Width / 2 + 50, Window.ClientBounds.Height / 2 + 50, 0);
            quad2.RenderBucketType    = RenderBucketType.Skip;
            quad2.SceneHints.CullHint = CullHint.Never;
            quad2.OrthoOrder          = 1; //Setting the ortho order less than quad1 means this will be drawn first when in the ortho render bucket
            quad2.SetRenderState(DepthStencilState.None);
            quad2.SetRenderState(RasterizerState.CullNone);
            orthos.AddChild(quad2);

            transparentTorus          = new Torus("TransparentSphere", 30, 30, 8, 16);
            transparentTorus.Material = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            transparentTorus.Material.SetParameter("MatDiffuse", Color.Green.ToVector3());
            transparentTorus.Material.SetParameter("Alpha", .75f);
            transparentTorus.SetRenderState(BlendState.AlphaBlendNonPremultiplied);
            transparentTorus.RenderBucketType = RenderBucketType.Skip;
            transparentTorus.Translation      = new Vector3(30, 10, 80);
            transpNode.AddChild(transparentTorus);

            transparentBox          = new Box("TransparentBox", 10, 10, 10);
            transparentBox.Material = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            transparentBox.Material.SetParameter("MatDiffuse", Color.DarkRed.ToVector3());
            transparentBox.Material.SetParameter("Alpha", .5f);
            transparentBox.SetRenderState(BlendState.AlphaBlendNonPremultiplied);
            transparentBox.RenderBucketType = RenderBucketType.Skip;
            transparentBox.Translation      = new Vector3(0, 10, 50);
            transpNode.AddChild(transparentBox);

            transparentTeapot          = new Teapot("TransparentTeapot");
            transparentTeapot.Material = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            transparentTeapot.Material.SetParameter("MatDiffuse", Color.LightGreen.ToVector3());
            transparentTeapot.Material.SetParameter("Alpha", .35f);
            transparentTeapot.SetRenderState(BlendState.AlphaBlendNonPremultiplied);
            transparentTeapot.RenderBucketType = RenderBucketType.Skip;
            transparentTeapot.Translation      = new Vector3(-10, 40, 40);
            transparentTeapot.SetScale(7.0f);
            transpNode.AddChild(transparentTeapot);

            opaqueBox1          = new Box("OpaqueBox", 10, 10, 10);
            opaqueBox1.Material = ContentManager.Load <Material>("LitBasicTexture.tem").Clone();
            opaqueBox1.Material.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//bricks_diff.dds"));
            opaqueBox1.RenderBucketType = RenderBucketType.Skip;
            opaqueBox1.Translation      = new Vector3(0, -10, -20);
            RootNode.AddChild(opaqueBox1);

            opaqueBox2          = new Box("OpaqueBox", 10, 10, 10);
            opaqueBox2.Material = ContentManager.Load <Material>("LitBasicTexture.tem").Clone();
            opaqueBox2.Material.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//bricks_diff.dds"));
            opaqueBox2.RenderBucketType = RenderBucketType.Skip;
            opaqueBox2.Translation      = new Vector3(0, 20, -20);
            RootNode.AddChild(opaqueBox2);

            opaqueBox3          = new Box("OpaqueBox", 10, 10, 10);
            opaqueBox3.Material = ContentManager.Load <Material>("LitBasicTexture.tem").Clone();
            opaqueBox3.Material.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//bricks_diff.dds"));
            opaqueBox3.RenderBucketType = RenderBucketType.Skip;
            opaqueBox3.Translation      = new Vector3(0, 50, -20);
            RootNode.AddChild(opaqueBox3);

            RootNode.SetModelBound(new BoundingBox());

            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.R, false), new InputAction(
                                                            delegate(GameTime time) {
                toggleRenderQueue = !toggleRenderQueue;
                Toggle(toggleRenderQueue, toggleTwoPass);
            }
                                                            )));
            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.T, false), new InputAction(
                                                            delegate(GameTime time) {
                toggleTwoPass = !toggleTwoPass;
                Toggle(toggleRenderQueue, toggleTwoPass);
            }
                                                            )));

            //Set up some text rendering
            batch = new SpriteBatch();
            font  = ContentManager.Load <SpriteFont>("Fonts//comicsans.fnt");
        }
Beispiel #23
0
 public void Register(LiteralNode contents)
 {
     Root.AddChild(contents);
 }
Beispiel #24
0
        protected override void LoadContent()
        {
            Window.Title = "Instancing Sample";
            ClearColor   = Color.Black;

            //Let's create a mesh that will serve as our data. We're technically not using the scene graph here, this is just a convience.
            //Maybe at some point the engine's scene graph will have a mesh structure that supports instancing, for now we have to do it ourselves.
            mesh = new Box("Box", 2, 2, 5);
            mesh.SetRandomColors();

            //We use the default lights from the root node, so all our instances will be lit.
            mesh.Lights.Set(RootNode.Lights);
            mesh.UpdateWorldLights(false);

            //Create a target object that all our instances will "look at"
            sphere          = new Sphere("Sphere", 30, 30, 10);
            sphere.Material = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            sphere.Material.SetParameter("MatDiffuse", Color.Yellow.ToVector3());
            RootNode.AddChild(sphere);

            // The mesh will have a vertex buffer that goes something like so:
            //
            //Position0 - Vector3
            //Normal0 - Vector3
            //Color0 - Color
            //TexCoord0 - Vector2
            //
            // Meanwhile, our second vertex buffer that contains the world transforms will look like this, since we're passing a 4x4 matrix:
            //
            //TexCoord0 - Vector4
            //TexCoord1 - Vector4
            //TexCoord2 - Vector4
            //TexCoord3 - Vector4
            //
            // When we set these two buffers at the same time (first to slot 0, second to slot 1), the engine automatically
            //merges the declarations and resolves conflicts such as duplicate semantic indices - in the order the
            //vertex buffers are set to the device, so in this example the semantic indices of the second buffer are all incremented
            //by one.

            VertexDeclaration decl = new VertexDeclaration(new VertexElement[] {
                new VertexElement(VertexSemantic.TextureCoordinate, 0, VertexFormat.Vector4, 0),
                new VertexElement(VertexSemantic.TextureCoordinate, 1, VertexFormat.Vector4, 16),
                new VertexElement(VertexSemantic.TextureCoordinate, 2, VertexFormat.Vector4, 32),
                new VertexElement(VertexSemantic.TextureCoordinate, 3, VertexFormat.Vector4, 48)
            });

            //We want a dynamic vertex buffer for the world transforms since we'll be updating each instance's
            //rotation to "look at" the sphere.
            worldTransforms = new VertexBuffer(decl, numInstances, ResourceUsage.Dynamic);
            transformArray  = new Matrix[numInstances];
            int index = 0;

            //Set the instances into a 2D grid on the XY plane.
            for (int x = 0; x < 16; x++)
            {
                for (int y = 0; y < 16; y++)
                {
                    Matrix transform = Matrix.FromTranslation(new Vector3((x - 7.5f) * 15.0f, (y - 7.5f) * 15.0f, 0.0f));
                    transformArray[index++] = transform;
                }
            }

            worldTransforms.SetData <Matrix>(transformArray);

            //Setup our vertex buffer bindings - the world transforms are set to an instance frequency of one, so for each
            //instance we'll use one "vertex" from that buffer (which is the world transform)
            buffers = new VertexBufferBinding[] { mesh.MeshData.VertexBuffer, new VertexBufferBinding(worldTransforms, 0, 1) };

            //Load a material we've created
            material = ContentManager.Load <Material>("Materials//InstancedMaterial.tem");
            material.SetParameter("DiffuseMap", ContentManager.Load <Texture>("Textures//rock_diff.dds"));
        }
Beispiel #25
0
        protected override void LoadContent()
        {
            ClearColor = Color.Black;
            shadowMap  = new RenderTarget2D(1024, 1024, false, SurfaceFormat.Single, DepthFormat.Depth24Stencil8);
            blurRT     = new RenderTarget2D(1024, 1024, false, SurfaceFormat.Single, DepthFormat.None);
            blurEffect = ContentManager.Load <Effect>("Shaders//GaussianBlur.fx");

            ModelLoaderParameters mlp = new ModelLoaderParameters();

            mlp.NormalGeneration   = NormalGeneration.Smooth;
            mlp.SwapWindingOrder   = true;
            mlp.PreferLitMaterials = true;

            rs      = new RasterizerState();
            rs.Cull = CullMode.Front;
            rs.BindRenderState();

            // mesh = new Sphere("Sphere", 50, 50, 20);
            mesh = ContentManager.Load <Mesh>("Models//statue.tebo");
            mesh.ComputeTangentBasis();
            Material mat = ContentManager.Load <Material>("LitBasicTexture.tem").Clone();

            mat.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//statue_diff.dds"));
            mat.SetParameter("NormalMap", ContentManager.Load <Texture2D>("Textures//statue_norm.dds"));
            mat.SetParameter("MatSpecular", new Vector3(.3f, .3f, .3f));
            mesh.SetMaterial(mat);

            Quad q = new Quad("Floor", 800, 800);

            q.Rotation    = Quaternion.FromAngleAxis(MathHelper.ToRadians(-90), Vector3.UnitX);
            q.Translation = new Vector3(0, -70, 0);
            q.Material    = ContentManager.Load <Material>("Materials//LitBasicTextureShadow.tem").Clone();
            q.Material.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//statue_diff.dds"));
            receiverMat = q.Material;
            receiverMat.SetParameter("MatSpecular", new Vector3(.3f, .3f, .3f));
            // mesh.SetMaterial(receiverMat);

            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.Enter, false), new InputAction(delegate(GameTime time) {
                receive = !receive;
                if (receive)
                {
                    mesh.SetMaterial(receiverMat);
                }
                else
                {
                    mesh.SetMaterial(mat);
                }
            })));
            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.C, false), new InputAction(delegate(GameTime time) {
                cullFront = !cullFront;
            })));

            DataBuffer <Vector2> texCoords = q.MeshData.TextureCoordinates;

            texCoords.Position = 0;
            texCoords.Set(new Vector2(0, 0));
            texCoords.Set(new Vector2(4, 0));
            texCoords.Set(new Vector2(4, 4));
            texCoords.Set(new Vector2(0, 4));
            q.MeshData.UpdateVertexData <Vector2>(VertexSemantic.TextureCoordinate, texCoords);
            RootNode.AddChild(q);

            sl = new SpotLight(new Vector3(100, 200, 10), new Vector3(-100, -200, -10), 5, 15);
            RootNode.RemoveAllLights();
            RootNode.AddLight(sl);
            RootNode.AddChild(mesh);


            shadowMat = new Material("ShadowMat");
            shadowMat.LoadEffect(ContentManager.Load <Effect>("Shaders//ShadowMapEffect.fx"));
            shadowMat.SetEngineParameter("LightWVP", Tesla.Core.EngineValue.WorldViewProjection);
            lightCam = new Camera();

            batch             = new SpriteBatch();
            dss               = new DepthStencilState();
            dss.DepthFunction = ComparisonFunction.LessEqual;
            dss.BindRenderState();

            float texOffsets = 0.5f + (0.5f / (float)shadowMap.Width);

            texMat = new Matrix(0.5f, 0.0f, 0.0f, 0.0f,
                                0.0f, -0.5f, 0.0f, 0.0f,
                                0.0f, 0.0f, 1.0f, 0.0f,
                                texOffsets, texOffsets, 0.0f, 1.0f);
            rtnode             = new Node("Node");
            rtnode.Translation = sl.Position;
            Node parent = new Node("Parent");

            parent.AddChild(rtnode);
            RootNode.AddChild(parent);
            parent.AddController(new Tesla.Scene.Extension.RotateController(Vector3.UnitY, 25));
        }
Beispiel #26
0
        protected override void LoadContent()
        {
            Window.Title = "Input Handling Sample";
            rotateSpeed  = 2.5f;
            speed        = 105.0f;

            Renderer.CurrentCamera.Position = new Vector3(0, 800, 100);
            Renderer.CurrentCamera.LookAt(Vector3.Zero, Vector3.Up);
            Renderer.CurrentCamera.Update();

            //Load our fancy pants racecar
            ModelLoaderParameters mlp = new ModelLoaderParameters();

            mlp.SwapWindingOrder   = true;
            mlp.NormalGeneration   = NormalGeneration.Crease;
            mlp.PreferLitMaterials = true;

            Spatial car = ContentManager.Load <Spatial>("Models//Jeep.dxs", mlp);

            car.SetModelBound(new BoundingBox());
            RootNode.AddChild(car);

            //Create an input layer, this layer will hold all of our controls and input response to the arrow keys, moving the car
            input = new InputLayer();

            //Input layers can be disabled or enabled, so you're able to logically group your inputs together and treat them as one unit.
            //E.g. if you have a screen menu and want the mouse enabled, but for gameplay do not want the mouse enabled.
            //Rather than disabling the whole layer, we'll just disable the first 5 triggers - which are the
            //FPS controls set in BasicApp.
            InputLayer.EnableTrigger(0, false);
            InputLayer.EnableTrigger(1, false);
            InputLayer.EnableTrigger(2, false);
            InputLayer.EnableTrigger(3, false);
            InputLayer.EnableTrigger(4, false);

            //Since we disabled the basicApp's input alyer, lets make sure we can get out of the app
            input.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.Escape, false),
                                                   new InputAction(delegate(GameTime time) {
                Exit();
            })));

            input.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.A, true), new InputAction(
                                                       delegate(GameTime time) {
                car.Rotation *= Quaternion.FromAngleAxis(rotateSpeed * (float)time.ElapsedTimeInSeconds, Vector3.Up);
            }
                                                       )));
            input.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.D, true), new InputAction(
                                                       delegate(GameTime time) {
                car.Rotation *= Quaternion.FromAngleAxis(-rotateSpeed * (float)time.ElapsedTimeInSeconds, Vector3.Up);
            }
                                                       )));

            input.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.W, true), new InputAction(
                                                       delegate(GameTime time) {
                //Usually a good idea to use the world properties, since this may be attached to a node that is moving also
                car.Translation -= car.WorldTransform.GetRotationVector(2) * speed * (float)time.ElapsedTimeInSeconds;
            }
                                                       )));
            input.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.S, true), new InputAction(
                                                       delegate(GameTime time) {
                car.Translation += car.WorldTransform.GetRotationVector(2) * speed * (float)time.ElapsedTimeInSeconds;
            }
                                                       )));

            //Add another point light to the scene
            PointLight pl = new PointLight();

            pl.Attenuate = false;
            pl.Position  = new Vector3(0, 0, 50);
            car.AddLight(pl);
        }
Beispiel #27
0
        protected override void LoadContent()
        {
            Window.Title = "Materials Sample";
            //Materials are a high level construct that are used to render objects. They contain the following:
            //
            //1. An effect shader that contains a set of techniques, where each techniques have a number of passes.
            //2. Render states for each pass.
            //3. Collection of uniform parameters.
            //4. Collection of engine parameters.
            //5. Material logic.
            //
            //The first three are simply an extension of using an Effect object directly (and for managing render states at the app level, opposed
            //to setting them in an effect file).
            //
            //Engine parameters are simply a binding between an uniform variable and an engine-defined value such as a World-View-Projection matrix,
            //camera position, time variables, etc. This binding allows this data to be served to the shader automatically per-frame.
            //
            //Material logic are similar to Spatial controllers as they allow the user to add pieces of logic that are executed when the material is
            //applied. This allows for the concept of "Pre-Shaders", where you compute values on the CPU and send that data to the GPU. This is useful
            //for computations that only should be done once, rather than for every vertex or pixel fragment (saving instructions and time). An
            //example of logic usage is how lighting is implemented in the engine - it's nothing more than a material logic that operates on the collection
            //of lights a renderable contains.
            //
            //
            //There are two ways to create a material - programmatically or via the engine's scripting functionality. Material scripts allow for the user
            //to device a material in a text file that can be used as a template for other scripts and changed without having to write any C# code.

            //Create a basic texture material
            Material myMaterial = new Material("MyMaterial");

            myMaterial.LoadEffect(ContentManager.Load <Effect>("BasicEffect.tebo").Clone());
            myMaterial.SetActiveTechnique("BasicTexture");
            myMaterial.SetParameter("DiffuseMap", ContentManager.Load <Texture2D>("Textures//rock_diff.dds"));
            myMaterial.SetParameter("DiffuseColor", Color.White);
            myMaterial.SetEngineParameter("WVP", EngineValue.WorldViewProjection);

            /* The above would look like this as a script:
             *
             * Material MyMaterial {
             *      Effect {
             *              File : BasicEffect.tebo
             *              Technique : BasicTexture
             *      }
             *
             *      MaterialParameters {
             *              Vector4 DiffuseColor : 1.0 1.0 1.0 1.0
             *              Texture2D DiffuseMap : Textures/rock_diff.dds
             *      }
             *
             *      EngineParameters {
             *              WorldViewProjection : WVP
             *      }
             * }*/

            /* Additionally, you can use an existing script as a template. The BasicTexture.tem is
             * a script already present in the engine's shader library and looks like the above script,
             * minus the texture2d. So we use the script, and simply add a new parameter.
             *
             * Material MyMaterial : BasicTexture.tem {
             *
             *      MaterialParameters {
             *              Texture2D DiffuseMap : Textures/rock_diff.dds
             *      }
             * }*/

            Material scriptMaterial = ContentManager.Load <Material>("Materials//SampleMaterial.tem").Clone();

            //To differentiate the two, lets set the scripted material's diffuse color to light blue
            scriptMaterial.SetParameter("DiffuseColor", Color.LightBlue);

            //Set our procedural material to the left.
            Box b1 = new Box("B1", 20, 20, 20);

            b1.Material    = myMaterial;
            b1.Translation = new Vector3(-50, 0, 0);
            RootNode.AddChild(b1);

            //Set our scripted material to the right.
            Box b2 = new Box("B2", 20, 20, 20);

            b2.Material    = scriptMaterial;
            b2.Translation = new Vector3(50, 0, 0);
            RootNode.AddChild(b2);

            RootNode.SetModelBound(new BoundingBox());
        }
Beispiel #28
0
        /// <summary>
        /// Please see the SceneGraph.rtf description for scene graph organization.
        /// </summary>
        protected override void LoadContent()
        {
            ClearColor   = Color.CornflowerBlue;
            Window.Title = "Scene Graph Sample";

            //Create the teapot sub-tree, we're also creating a small box showing the position of
            //the node in world space
            Node teapotParent       = new Node("TeapotParent");
            Box  teapotParentVisual = new Box("TeapotParentVisual", 1f, 1f, 1f);

            teapotParentVisual.Material = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            teapotParent.AddChild(teapotParentVisual);

            //Set a rotate controller onto the teapot parent, so it'll rotate every frame
            teapotParent.AddController(new RotateController(Vector3.UnitY, 25));

            //Create the teapot mesh
            Teapot teapot = new Teapot("Teapot");

            //Load up a default lit color material
            teapot.Material = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            //Create another rotate controller that will rotate the teapot about its X-Axis
            //45 degrees per second. This shows how we can -easily- concatenate transforms
            //using the hierarchy of the scene graph.
            teapot.AddController(new RotateController(Vector3.UnitX, 45f));

            //Set a red color to the material.
            teapot.Material.SetParameter("MatDiffuse", Color.Crimson.ToVector3());
            teapot.Scale = new Vector3(5f, 5f, 5f);

            //Position and add to parent
            teapot.Translation = new Vector3(-50, 0, 0);
            teapotParent.AddChild(teapot);

            //Add the teapot sub tree to the root.
            RootNode.AddChild(teapotParent);

            //Add a white light to the root node
            RootNode.RemoveAllLights();
            PointLight pl = new PointLight();

            pl.Attenuate = false;
            pl.Position  = new Vector3(-100, 50, 100);
            RootNode.AddLight(pl);

            //Create the box
            Box box = new Box("Box", 10, 10, 10);

            box.Translation = new Vector3(50, -50, 0);
            box.Material    = ContentManager.Load <Material>("LitBasicColor.tem").Clone();
            box.Material.SetParameter("MatDiffuse", Color.Gray.ToVector3());

            //Set the box to only use lights that are attached to it
            box.SceneHints.LightCombineHint = LightCombineHint.Local;

            //Create a green point light
            PointLight pl2 = new PointLight();

            pl2.Attenuate = false;
            pl2.Diffuse   = Color.Green;
            pl2.Position  = new Vector3(100, 50, 100);
            box.AddLight(pl2);

            //Add the box to the root
            RootNode.AddChild(box);

            //Set a bounding box to be used as the volume for each node/mesh in the scene graph.
            RootNode.SetModelBound(new BoundingBox());

            //Create some input handling to show how you can apply
            //a scaling value to a parent node (this case the scene Root),
            //and see it be applied to all children.
            InputLayer.RegisterTrigger(new InputTrigger(new KeyPressedCondition(Keys.J, false), new InputAction(delegate(GameTime time) {
                if (RootNode.Controllers.Count > 0)
                {
                    RootNode.RemoveAllControllers();
                    RootNode.SetScale(1.0f);
                    scaleOn = false;
                }
                else
                {
                    RootNode.AddController(new ScaleController(1.0f, .1f, 2.0f));
                    scaleOn = true;
                }
            })));

            batch = new SpriteBatch();
            font  = ContentManager.Load <SpriteFont>("Fonts//comicsans.fnt");
        }
Beispiel #29
0
        private void ParseUntil(RootNode baseNode, TokenKind?stopToken = null)
        {
            while (_enumerator.MoveNext())
            {
                var token = _enumerator.Current;
                if (token.Kind == stopToken)
                {
                    break;
                }
                switch (token.Kind)
                {
                case TokenKind.DEF:
                {
                    DefStatement temp = null;
                    switch (baseNode)
                    {
                    case IVariableTableContainer tableContainer:
                    {
                        temp = ParseDef(new Dictionary <string, int>(tableContainer.varTable));
                        break;
                    }

                    default:
                    {
                        temp = ParseDef(new Dictionary <string, int>(_base.varTable));
                        break;
                    }
                    }
                    baseNode.AddChild(temp);
                    break;
                }

                case TokenKind.NAME: {
                    //Console.WriteLine(_enumerator.Current.data);
                    if (_enumerator.MoveNext())
                    {
                        if (_enumerator.Current.Kind == TokenKind.EQUAL)
                        {
                            _enumerator.MovePrevious();
                            var name = _enumerator.Current.data;
                            _enumerator.MoveNext();
                            _enumerator.MoveNext();
                            var expr = ParseExpr();
                            baseNode.AddChild(new AssignStatement(
                                                  _enumerator.Current.row,
                                                  _enumerator.Current.column,
                                                  name, expr));
                            switch (baseNode)
                            {
                            case IVariableTableContainer tableContainer:
                            {
                                tableContainer.AddVar(name);
                                break;
                            }

                            default:
                            {
                                _currentNameSpace.AddVar(name);
                                break;
                            }
                            }
                        }
                        else if (_enumerator.Current.Kind == TokenKind.PLUSEQUAL ||
                                 _enumerator.Current.Kind == TokenKind.MINEQUAL ||
                                 _enumerator.Current.Kind == TokenKind.STAREQUAL ||
                                 _enumerator.Current.Kind == TokenKind.SLASHEQUAL)
                        {
                            _enumerator.MovePrevious();
                            var name = _enumerator.Current.data;
                            var row  = _enumerator.Current.row;
                            var col  = _enumerator.Current.column;
                            switch (baseNode)
                            {
                            case IVariableTableContainer tableContainer:
                            {
                                if (!tableContainer.HaveVariable(name))
                                {
                                    throw new CompilerException(
                                              $"Name {name} is not defined at {_enumerator.Current.row}:{_enumerator.Current.column}",
                                              _enumerator.Current.row, _enumerator.Current.column);
                                }
                                break;
                            }

                            default:
                            {
                                if (!_currentNameSpace.HaveVariable(name))
                                {
                                    throw new CompilerException(
                                              $"Name {name} is not defined at {_enumerator.Current.row}:{_enumerator.Current.column}",
                                              _enumerator.Current.row, _enumerator.Current.column);
                                }
                                break;
                            }
                            }
                            _enumerator.MoveNext();
                            //var op = _enumerator.Current.Kind;
                            var op = _enumerator.Current.Kind switch
                            {
                                TokenKind.PLUSEQUAL => TokenKind.PLUS,
                                TokenKind.MINEQUAL => TokenKind.MINUS,
                                TokenKind.STAREQUAL => TokenKind.STAR,
                                TokenKind.SLASHEQUAL => TokenKind.SLASH
                            };
                            if (_enumerator.MoveNext())
                            {
                                baseNode.AddChild(new AssignStatement(
                                                      _enumerator.Current.row,
                                                      _enumerator.Current.column,
                                                      name,
                                                      new BinOp(_enumerator.Current.row,
                                                                _enumerator.Current.column,
                                                                op,
                                                                new VarExpression(row,
                                                                                  col,
                                                                                  name),
                                                                ParseExpr()
                                                                )));
                            }
                        }
                        else if (_enumerator.Current.Kind == TokenKind.LPAR)
                        {
                            _enumerator.MovePrevious();
                            var tempEx = ParseExpr();
                            var temp   = new ExprStatement(tempEx.Row, tempEx.Column, tempEx);
                            //var temp = ParseName();
                            baseNode.AddChild(temp);
                            // if (!_base.root.GetChildren()
                            //     .Any(def =>
                            //         def is DefStatement d &&
                            //         d.Name == temp.Name))
                            // {
                            //     throw new SyntaxException(
                            //         $"Name {temp.Name} is not defined at {temp.Row + 1}:{temp.Column}",
                            //         temp.Row, temp.Column);
                            // }
                            this.MatchIndentation();
                            break;
                        }
                        else
                        {
                            _enumerator.MovePrevious();
                            baseNode.AddChild(new ExprStatement(
                                                  _enumerator.Current.row,
                                                  _enumerator.Current.column,
                                                  ParseExpr()));
                            ;
                        }
                    }
                    break;
                }

                case TokenKind.IF:
                {
                    var temp = ParseConditional();
                    baseNode.AddChild(temp);
                    //_enumerator.MovePrevious();
                    break;
                }

                case TokenKind.INT:
                case TokenKind.MINUS:
                case TokenKind.TILDE:
                case TokenKind.EXCLAMINATION:
                case TokenKind.LPAR:
                {
                    var temp = new ExprStatement(_enumerator.Current.row,
                                                 _enumerator.Current.column,
                                                 ParseExpr());
                    //Console.WriteLine(temp.ToString());
                    baseNode.AddChild(temp);
                    MatchIndentationCurrent();
                    break;
                }

                case TokenKind.WHILE:
                {
                    var temp = ParseWhileLoop();
                    baseNode.AddChild(temp);
                    break;
                }

                case TokenKind.BREAK:
                {
                    if (_currentLoop == null)
                    {
                        throw new CompilerException($"Break is outside of loop at {_enumerator.Current.row}:" +
                                                    $"{_enumerator.Current.column}",
                                                    _enumerator.Current.row,
                                                    _enumerator.Current.column);
                    }
                    baseNode.AddChild(new BreakStatement(_enumerator.Current.row,
                                                         _enumerator.Current.column));
                    break;
                }

                case TokenKind.CONTINUE:
                {
                    if (_currentLoop == null)
                    {
                        throw new CompilerException($"Continue is outside of loop at {_enumerator.Current.row}:" +
                                                    $"{_enumerator.Current.column}",
                                                    _enumerator.Current.row,
                                                    _enumerator.Current.column);
                    }
                    baseNode.AddChild(new ContinueStatement(_enumerator.Current.row,
                                                            _enumerator.Current.column));
                    break;
                }

                case TokenKind.PRINT:
                {
                    var temp = new Print(_enumerator.Current.row, _enumerator.Current.column);
                    Match(TokenKind.LPAR);
                    temp.expr = ParseExpr();
                    _enumerator.MovePrevious();
                    MatchCurrent(TokenKind.RPAR);
                    baseNode.AddChild(temp);
                    break;
                }

                case TokenKind.RETURN:
                {
                    if (_currentNameSpace.GetType() != typeof(DefStatement))
                    {
                        throw new CompilerException($"Return outside of function at {_enumerator.Current.row}:" +
                                                    $"{_enumerator.Current.column}",
                                                    _enumerator.Current.row,
                                                    _enumerator.Current.column);
                    }
                    var t = _enumerator.Current;
                    _enumerator.MovePrevious();
                    baseNode.AddChild(new ReturnStatement(t.row, t.column, MatchReturn()));
                    break;
                }

                default:
                {
                    break;
                }
                }
            }
        }