private void MapArguments(Arguments arguments, Model.Arguments model, HashSet<string> stackTrace)
        {
            if (!string.IsNullOrEmpty(arguments.template))
            {
                if (stackTrace.Contains(arguments.template, StringComparer.InvariantCulture))
                    throw new TemplateException(string.Format(Strings.XmlTemplateCircularReference, arguments.template));

                var template = GetTemplate(arguments.template, TemplateType.Arguments);

                stackTrace.Add(arguments.template);
                MapArguments(template.Item, model, stackTrace);
            }

            if (arguments.Argument != null)
            {
                foreach (var argument in arguments.Argument)
                    model.Add(argument.name, argument.Value);
            }
        }
Exemplo n.º 2
0
 public void AddItem(Model.Cart cart, string productCode, int saleUnitValue, int packagingValue, int quantity, Model.Price salePrice, Model.Price recyclePrice)
 {
     quantity = Math.Max(1, quantity);
     var existing = cart.Items.SingleOrDefault(i => i.ProductCode.Equals(productCode, StringComparison.InvariantCultureIgnoreCase));
     if (existing == null)
     {
         cart.Add(new Model.CartItem()
         {
             ProductCode = productCode,
             Quantity = quantity,
             SalePrice = salePrice,
             SaleUnitValue = saleUnitValue,
             Packaging = packagingValue,
             RecyclePrice = recyclePrice ?? new Model.Price(0m,0d),
         });
     }
     else
     {
         existing.Quantity += quantity;
     }
 }
Exemplo n.º 3
0
        public override void Run(string path)
        {
            const int perFace = 4;

            int[] coords =
            {
                1,  -1,  1,
                -1, -1,  1,
                -1, -1, -1,
                1,  -1, -1,

                1,  -1,  1,
                1,   1,  1,
                -1,  1,  1,
                -1, -1,  1,

                1,   1, -1,
                1,   1,  1,
                1,  -1,  1,
                1,  -1, -1,

                1,  -1, -1,
                -1, -1, -1,
                -1,  1, -1,
                1,   1, -1,

                -1,  1, -1,
                -1, -1, -1,
                -1, -1,  1,
                -1,  1,  1,

                1,   1, -1,
                -1,  1, -1,
                -1,  1,  1,
                1,   1, 1
            };

            Model model = new Model();

            for (int f = 0; f < coords.Length / (perFace * 3); ++f)
            {
                IList <Point3> corners = new List <Point3>();

                for (int c = 0; c < perFace; ++c)
                {
                    int offset = (f * perFace + c) * 3;

                    corners.Add(new Point3(coords[offset] + 2,
                                           coords[offset + 1],
                                           coords[offset + 2]));
                }

                model.Add(corners);
            }

            for (int f = 0; f < coords.Length / (perFace * 3); ++f)
            {
                IList <Point3> corners = new List <Point3>();

                for (int c = 0; c < perFace; ++c)
                {
                    int offset = (f * perFace + c) * 3;

                    corners.Add(new Point3(coords[offset],
                                           coords[offset + 1] + 2,
                                           coords[offset + 2]));
                }

                model.Add(corners);
            }

            for (int f = 0; f < coords.Length / (perFace * 3); ++f)
            {
                IList <Point3> corners = new List <Point3>();

                for (int c = 0; c < perFace; ++c)
                {
                    int offset = (f * perFace + c) * 3;

                    corners.Add(new Point3(coords[offset],
                                           coords[offset + 1],
                                           coords[offset + 2] + 2));
                }

                model.Add(corners);
            }

            model.WriteSketchUpFile(path + @"\ThreeCubesWelded.skp");
        }
Exemplo n.º 4
0
        public Entity AttachDebugShapeAsChild()
        {
            System.Numerics.Vector3 min, max;
            if (ColliderShape is IConvexShape ics)
            {
                ics.ComputeBounds(BepuHelpers.ToBepu(Quaternion.Identity), out min, out max);
            }
            else if (ColliderShape is BepuPhysics.Collidables.Mesh cm)
            {
                cm.ComputeBounds(BepuHelpers.ToBepu(Quaternion.Identity), out min, out max);
            }
            else
            {
                return(null);
            }

            Vector3 centerOffset = BepuHelpers.ToXenko(max + min) * 0.5f;

            Game g = ServiceRegistry.instance.GetService <IGame>() as Game;

            if (debugShapeMaterial == null)
            {
                var materialDescription = new MaterialDescriptor
                {
                    Attributes =
                    {
                        DiffuseModel = new MaterialDiffuseLambertModelFeature(),
                        Diffuse      = new MaterialDiffuseMapFeature(new ComputeColor {
                            Key      = MaterialKeys.DiffuseValue
                        })
                    }
                };

                debugShapeMaterial = Material.New(g.GraphicsDevice, materialDescription);
                debugShapeMaterial.Passes[0].Parameters.Set(MaterialKeys.DiffuseValue, Color.Red);

                var meshDraw = GeometricPrimitive.Cube.New(g.GraphicsDevice, Vector3.One).ToMeshDraw();

                cubeMesh = new Rendering.Mesh {
                    Draw = meshDraw
                };
            }

            Entity e = new Entity(Entity.Name + "-physicsBB");

            Model m = new Model();

            m.Add(debugShapeMaterial);
            m.Meshes.Add(cubeMesh);

            ModelComponent mc = e.GetOrCreate <ModelComponent>();

            mc.Model = m;

            e.Transform.Scale    = new Vector3(max.X - min.X, max.Y - min.Y, max.Z - min.Z) / Entity.Transform.WorldScale();
            e.Transform.Position = centerOffset / Entity.Transform.WorldScale();
            if (this is BepuRigidbodyComponent rb && rb.IgnorePhysicsRotation)
            {
                e.Transform.Rotation = Rotation;
            }
            e.Transform.Parent = Entity.Transform;

            return(e);
        }
Exemplo n.º 5
0
 public void Add(int val)
 {
     _m.Add(val);
 }
Exemplo n.º 6
0
        public void TestCanvasDataWithOutSegments()
        {
            IFigure      figure  = new Figure();
            IContour     contour = new MidSurfaceNameSpace.Primitive.Contour();
            List <Point> pillar  = new List <Point>();
            Point        p1      = new Point();

            p1.X = 1;
            p1.Y = 1;
            Point p2 = new Point();

            p2.X = 2;
            p2.Y = 2;
            pillar.Add(p1);
            pillar.Add(p2);
            ISegment segment = new Segment(new BezierCurve(), pillar);

            contour.Add(segment);
            pillar = new List <Point>();
            p1     = new Point();
            p1.X   = 3;
            p1.Y   = 3;
            p2     = new Point();
            p2.X   = 4;
            p2.Y   = 4;
            pillar.Add(p1);
            pillar.Add(p2);
            segment = new Segment(new BezierCurve(), pillar);
            contour.Add(segment);
            figure.Add(contour);

            contour = new MidSurfaceNameSpace.Primitive.Contour();
            pillar  = new List <Point>();
            p1      = new Point();
            p1.X    = 5;
            p1.Y    = 5;
            p2      = new Point();
            p2.X    = 6;
            p2.Y    = 6;
            pillar.Add(p1);
            pillar.Add(p2);
            segment = new Segment(new BezierCurve(), pillar);
            contour.Add(segment);
            pillar = new List <Point>();
            p1     = new Point();
            p1.X   = 7;
            p1.Y   = 7;
            p2     = new Point();
            p2.X   = 8;
            p2.Y   = 8;
            pillar.Add(p1);
            pillar.Add(p2);
            segment = new Segment(new BezierCurve(), pillar);
            contour.Add(segment);

            figure.Add(contour);
            IModel model = new Model();

            model.Add(figure);
            IEnumerable <ISegment> ccc = model.GetCanvasData();
            MSModel     msmodel        = new MSModel(model);
            List <bool> removed        = new List <bool>()
            {
                true, false, false, true
            };

            msmodel.Removed = removed;
            int             counter = msmodel.GetCanvasData().Count();
            List <ISegment> ccc1    = msmodel.GetCanvasData().ToList();

            Assert.AreEqual(counter, 2);
            Assert.AreEqual(ccc1[0].GetPillar()[0], new Point(3, 3));
            Assert.AreEqual(ccc1[0].GetPillar()[1], new Point(4, 4));
            Assert.AreEqual(ccc1[1].GetPillar()[0], new Point(5, 5));
            Assert.AreEqual(ccc1[1].GetPillar()[1], new Point(6, 6));
        }
Exemplo n.º 7
0
        public void DoImportStrings(string filename)
        {
            System.Xml.XPath.XPathDocument  xdoc = new System.Xml.XPath.XPathDocument(filename);
            System.Xml.XPath.XPathNavigator nav  = xdoc.CreateNavigator();

            StringTableSet previousSTS = _CurrentStringTableSet;

            SelectedStringTableSet = -1;
            System.Xml.XPath.XPathNodeIterator xsts = nav.Select("/pjstbleditorexport/StringTableSet");
            while (xsts.MoveNext())
            {
                ulong iid = Package.NewInstance() >> 8;
                System.Xml.XPath.XPathNavigator xiid = xsts.Current.SelectSingleNode("iid");
                if (xiid != null)
                {
                    if (xiid.Value.ToLower().StartsWith("0x"))
                    {
                        ulong.TryParse(xiid.Value.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out iid);
                    }
                }

                Model.Add(iid);
                StringTableSet sts = Model[iid];

                System.Xml.XPath.XPathNodeIterator stringSets = xsts.Current.Select("stringSets/stringSet");
                while (stringSets.MoveNext())
                {
                    ulong guid;
                    System.Xml.XPath.XPathNavigator xguid = stringSets.Current.SelectSingleNode("guid");
                    if (xguid == null)
                    {
                        continue;
                    }
                    if (!xguid.Value.ToLower().StartsWith("0x"))
                    {
                        continue;
                    }
                    if (!ulong.TryParse(xguid.Value.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out guid))
                    {
                        continue;
                    }

                    Language language;
                    System.Xml.XPath.XPathNavigator xlanguage = stringSets.Current.SelectSingleNode("language");
                    if (xlanguage == null)
                    {
                        continue;
                    }
                    if (!Enum.TryParse <Language>(xlanguage.Value, out language))
                    {
                        continue;
                    }

                    string value;
                    System.Xml.XPath.XPathNavigator xvalue = stringSets.Current.SelectSingleNode("value");
                    if (xvalue == null)
                    {
                        continue;
                    }
                    value = xvalue.Value;

                    sts[guid, language] = value;
                }
            }
            OnStringTableSetsChanged();
            SelectedStringTableSet = Model.Count() - 1;
        }
Exemplo n.º 8
0
        public void Generate(IServiceRegistry services, Model model)
        {
            if (services == null)
            {
                throw new ArgumentNullException("services");
            }
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var graphicsDevice = services.GetSafeServiceAs <IGraphicsDeviceService>().GraphicsDevice;

            var data = this.CreatePrimitiveMeshData();

            if (data.Vertices.Length == 0)
            {
                throw new InvalidOperationException("Invalid GeometricPrimitive [{0}]. Expecting non-zero Vertices array");
            }

            var boundingBox = BoundingBox.Empty;

            for (int i = 0; i < data.Vertices.Length; i++)
            {
                BoundingBox.Merge(ref boundingBox, ref data.Vertices[i].Position, out boundingBox);
            }

            BoundingSphere boundingSphere;

            unsafe
            {
                fixed(void *verticesPtr = data.Vertices)
                BoundingSphere.FromPoints((IntPtr)verticesPtr, 0, data.Vertices.Length, VertexPositionNormalTexture.Size, out boundingSphere);
            }

            var originalLayout = data.Vertices[0].GetLayout();

            // Generate Tangent/BiNormal vectors
            var resultWithTangentBiNormal = VertexHelper.GenerateTangentBinormal(originalLayout, data.Vertices, data.Indices);

            // Generate Multitexcoords
            var result = VertexHelper.GenerateMultiTextureCoordinates(resultWithTangentBiNormal);

            var meshDraw = new MeshDraw();

            var layout       = result.Layout;
            var vertexBuffer = result.VertexBuffer;
            var indices      = data.Indices;

            if (indices.Length < 0xFFFF)
            {
                var indicesShort = new ushort[indices.Length];
                for (int i = 0; i < indicesShort.Length; i++)
                {
                    indicesShort[i] = (ushort)indices[i];
                }
                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indicesShort).RecreateWith(indicesShort), false, indices.Length);
            }
            else
            {
                if (graphicsDevice.Features.Profile <= GraphicsProfile.Level_9_3)
                {
                    throw new InvalidOperationException("Cannot generate more than 65535 indices on feature level HW <= 9.3");
                }

                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices).RecreateWith(indices), true, indices.Length);
            }

            meshDraw.VertexBuffers = new[] { new VertexBufferBinding(Buffer.New(graphicsDevice, vertexBuffer, BufferFlags.VertexBuffer).RecreateWith(vertexBuffer), layout, data.Vertices.Length) };

            meshDraw.DrawCount     = indices.Length;
            meshDraw.PrimitiveType = PrimitiveType.TriangleList;

            var mesh = new Mesh {
                Draw = meshDraw, BoundingBox = boundingBox, BoundingSphere = boundingSphere
            };

            model.BoundingBox    = boundingBox;
            model.BoundingSphere = boundingSphere;
            model.Add(mesh);

            if (MaterialInstance != null && MaterialInstance.Material != null)
            {
                model.Materials.Add(MaterialInstance);
            }
        }
Exemplo n.º 9
0
        public override void Run(string path)
        {
            const int perFace = 4;

            // Define all of the coordinates needed for six faces
            // of a cube.

            int[] coords =
            {
                1,  -1,  1,
                -1, -1,  1,
                -1, -1, -1,
                1,  -1, -1,

                1,  -1,  1,
                1,   1,  1,
                -1,  1,  1,
                -1, -1,  1,

                1,   1, -1,
                1,   1,  1,
                1,  -1,  1,
                1,  -1, -1,

                1,  -1, -1,
                -1, -1, -1,
                -1,  1, -1,
                1,   1, -1,

                -1,  1, -1,
                -1, -1, -1,
                -1, -1,  1,
                -1,  1,  1,

                1,   1, -1,
                -1,  1, -1,
                -1,  1,  1,
                1,   1, 1
            };

            Model model = new Model();

            // Convert the coordinates to sets that each define a quad.

            for (int f = 0; f < coords.Length / (perFace * 3); ++f)
            {
                IList <Point3> corners = new List <Point3>();

                // Extract four coordinates at a time into a list.

                for (int c = 0; c < perFace; ++c)
                {
                    int offset = (f * perFace + c) * 3;

                    corners.Add(new Point3(coords[offset],
                                           coords[offset + 1],
                                           coords[offset + 2]));
                }

                // Add another quad to the model.

                model.Add(corners);
            }

            model.WriteSketchUpFile(path + @"\PlainCube.skp");
        }
Exemplo n.º 10
0
        private static void BuildSmsTestModel()
        {
            EntityField field = null;

            /** User **/
            EntityClass user = new EntityClass();
            user.Name = "Principal";
            user.Visibility = "public";

            field = new EntityField();
            field.Name = "Id";
            field.IsPrimaryKey = true;
            field.Type = new Int();
            user.Fields.Add(field);

            /** IDescription Definition **/
            EntityInterface iDescription = new EntityInterface();
            iDescription.Name = "IDescription";
            iDescription.Visibility = "public";
            EntityMethod getDescription = new EntityMethod();
            getDescription.Name = "GetDescription";
            EntityParameter param = new EntityParameter();
            param.IsReturn = true;
            param.Type = IntrinsicTypes.Create( "System.String" );
            getDescription.ReturnEntity = param;
            iDescription.Methods.Add(getDescription);

            /** Category Definition **/

            EntityClass category = new EntityClass();
            category.Name = "Category";
            category.Visibility = "public";
            //category.Interfaces.Add(iDescription);

            field = new EntityField();
            field.Name = "Id";
            field.IsPrimaryKey = true;
            field.Type = new Int();
            category.Fields.Add(field);

            field = new EntityField();
            field.Name = "Description";
            field.IsRequired = true;
            field.MaxSize = 500;
            field.Type = new Loki.DataRepresentation.IntrinsicEntities.String();
            category.Fields.Add(field);

            /** Sms Definition **/

            EntityClass message = new EntityClass();
            message.Name = "SmsBase";
            message.IsAbstract = true;
            message.Visibility = "public";
            //message.Interfaces.Add(iDescription);

            field = new EntityField();
            field.Name = "Id";
            field.IsPrimaryKey = true;
            field.Type = new Int();
            message.Fields.Add(field);

            field = new EntityField();
            field.Name = "Description";
            field.IsRequired = true;
            field.MaxSize = 500;
            field.Default = "No Description";
            field.Type = new Loki.DataRepresentation.IntrinsicEntities.String();
            message.Fields.Add(field);

            field = new EntityField();
            field.Name = "Category";
            field.Type = category;
            field.Mult = Multiplicity.ManyToOne;
            field.IsRequired = true;
            message.Fields.Add(field);

            field = new EntityField();
            field.Name = "Principal";
            field.Type = user;
            field.Mult = Multiplicity.ManyToOne;
            field.IsRequired = true;
            message.Fields.Add(field);

            field = new EntityField();
            field.Name = "Messages";
            field.Type = message;
            field.Mult = Multiplicity.OneToMany;
            field.InfoOnly = true;
            user.Fields.Add(field);

            field = new EntityField();
            field.Name = "Messages";
            field.Type = message;
            field.InfoOnly = true;
            field.Mult = Multiplicity.OneToMany;
            category.Fields.Add(field);

            /** ImageSms **/
            EntityClass imageSms = new EntityClass();
            imageSms.Name = "ImageSms";
            imageSms.Visibility = "public";
            imageSms.Parent = message;

            field = new EntityField();
            field.Name = "ImageUrl";
            field.Type = new Loki.DataRepresentation.IntrinsicEntities.String();
            field.IsRequired = true;
            field.Default = "#";
            imageSms.Fields.Add(field);

            /** TextSms **/
            EntityClass textSms = new EntityClass();
            textSms.Name = "TextSms";
            textSms.Visibility = "public";
            textSms.Parent = message;

            field = new EntityField();
            field.Name = "Text";
            field.Type = new Loki.DataRepresentation.IntrinsicEntities.String();
            field.IsRequired = true;
            field.Default = "Empty";
            textSms.Fields.Add(field);

            /** Setting up project **/
            Model list = new Model();
            list.Add(category);
            list.Add(iDescription);
            list.Add(user);
            list.Add(message);
            list.Add(imageSms);
            list.Add(textSms);
            smsTestModel.Model = list;
        }
Exemplo n.º 11
0
        /// <summary>
        /// In this thread, try to create a model that uses the given amount of memory
        /// </summary>
        /// <param name="solverType">The type of the underlying solver to be used.</param>
        /// <param name="memoryGb">The amount of memory in GB to be used by this worker.</param>
        private void SonnetStressTestWorker(Type solverType, double memoryGb)
        {
            try
            {
                string threadid = System.Threading.Thread.CurrentThread.Name;
                Model  model    = new Model();
                Solver solver   = new Solver(model, solverType);

                Console.WriteLine("Available Memory (GB) Now: " + Utils.AvailableMemoryGb);
                Console.WriteLine("Current process Memory (GB) Now: " + Utils.ProcessMemoryGb);
                Console.WriteLine("Attempting to use (GB): " + memoryGb);
                // N = 3K, M = 30K, Z=100 requires about 110MB in 32-bit and 140MB in 64-bit mode.
                // Note: Arguably only M and Z matter, but we scall also N
                double f;
                if (IntPtr.Size == 4)
                {
                    f = memoryGb / 0.110;
                }
                else
                {
                    f = memoryGb / 0.140;
                }

                // Somehow the memory usage is much less on Windows 10 with .NET 4.7, so multiply by 13
                // the stress test
                int N = (int)(f * 3000);  // number of variables
                int M = (int)(f * 30000); // number of rangeconstraints
                int p = M / 10;
                int Z = 100;              // number nonzeros per constraint

                Variable   x    = new Variable();
                Variable[] vars = Variable.New(N);

                for (int m = 0; m < M; m++)
                {
                    if (m % p == 0)
                    {
                        Console.WriteLine(string.Format("Thread {0}: Building {1}", threadid, (1.0 * m / M).ToString("p")));
                    }
                    Expression expr = new Expression();
                    expr.Add(x);

                    for (int z = 0; z < Z; z++)
                    {
                        int i = (z + m) % N; // always between 0 and N-1
                        expr.Add(vars[i]);
                    }

                    int available = m;

                    string          rowName = "MyConstraint(" + m + ")";
                    RangeConstraint con     = (RangeConstraint)model.Add(rowName,
                                                                         -model.Infinity <= expr <= available);

                    expr.Assemble();
                    Assert.IsTrue(expr.NumberOfCoefficients == Z + 1);

                    expr.Clear();
                }

                Console.WriteLine(string.Format("Thread {0}: Start Generate... (this can take a while)", threadid));

                solver.Generate();

                Assert.IsTrue(solver.OsiSolver.getNumRows() == model.NumberOfConstraints);
                Assert.IsTrue(model.NumberOfConstraints == M);
                Assert.IsTrue(solver.OsiSolver.getNumElements() == M * (Z + 1));
                GC.Collect();
                Console.WriteLine("Available Memory (GB) Now: " + Utils.AvailableMemoryGb);
                Console.WriteLine("Current process Memory (GB) Now: " + Utils.ProcessMemoryGb);
                Console.WriteLine(string.Format("Thread {0}: Finished", threadid));
                model.Clear();
                Console.WriteLine(string.Format("Thread {0}: Closed", threadid));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
                Console.WriteLine(exception.StackTrace.ToString());
                Console.WriteLine("Available Memory (GB) Now: " + Utils.AvailableMemoryGb);
                Console.WriteLine("Current process Memory (GB) Now: " + Utils.ProcessMemoryGb);

                Assert.Fail("Stress test failed. Could be out-of-memory.");
                throw;
                // could be out-of-memory... Can we examine the SEHException?
            }
        }
Exemplo n.º 12
0
        private NavigationMeshDebugVisual CreateDebugVisual(NavigationMesh navigationMesh, NavigationMesh previousNavigationMesh)
        {
            NavigationMeshDebugVisual ret = new NavigationMeshDebugVisual();

            ret.DebugEntity = new Entity($"Debug entity for navigation mesh");

            // Create a visual for every layer with a separate color
            using (var layers = navigationMesh.Layers.GetEnumerator())
            {
                while (layers.MoveNext())
                {
                    Model model = new Model();

                    var currentLayer = layers.Current.Value;
                    var currentId    = layers.Current.Key;

                    NavigationMeshDisplayGroup displayGroup;
                    if (!groupDisplaySettings.TryGetValue(currentId, out displayGroup))
                    {
                        continue; // No display settings for this group
                    }
                    model.Add(displayGroup.Material);
                    model.Add(displayGroup.HighlightMaterial);

                    foreach (var p in currentLayer.Tiles)
                    {
                        bool updated = true;

                        NavigationMeshTile tile = p.Value;

                        // Extract vertex data
                        List <Vector3> tileVertexList = new List <Vector3>();
                        List <int>     tileIndexList  = new List <int>();
                        if (!tile.GetTileVertices(tileVertexList, tileIndexList))
                        {
                            continue;
                        }

                        // Check if updated
                        NavigationMeshLayer sourceLayer;
                        if (previousNavigationMesh != null && previousNavigationMesh.Layers.TryGetValue(currentId, out sourceLayer))
                        {
                            NavigationMeshTile oldTile = sourceLayer.FindTile(p.Key);
                            if (oldTile != null && oldTile.Data.SequenceEqual(tile.Data))
                            {
                                updated = false;
                            }
                        }

                        // Stack layers vertically
                        Vector3 offset = new Vector3(0.0f, LayerHeightMultiplier * displayGroup.Index, 0.0f);

                        // Calculate mesh bounding box from navigation mesh points
                        BoundingBox bb = BoundingBox.Empty;

                        List <VertexPositionNormalTexture> meshVertices = new List <VertexPositionNormalTexture>();
                        for (int i = 0; i < tileVertexList.Count; i++)
                        {
                            Vector3 position = tileVertexList[i] + offset;
                            BoundingBox.Merge(ref bb, ref position, out bb);

                            VertexPositionNormalTexture vert = new VertexPositionNormalTexture();
                            vert.Position          = position;
                            vert.Normal            = Vector3.UnitY;
                            vert.TextureCoordinate = new Vector2(0.5f, 0.5f);
                            meshVertices.Add(vert);
                        }

                        MeshDraw draw;
                        using (var meshData = new GeometricMeshData <VertexPositionNormalTexture>(meshVertices.ToArray(), tileIndexList.ToArray(), true))
                        {
                            GeometricPrimitive primitive = new GeometricPrimitive(game.GraphicsDevice, meshData);
                            ret.GeneratedDynamicPrimitives.Add(primitive);
                            draw = primitive.ToMeshDraw();
                        }

                        Mesh mesh = new Mesh
                        {
                            Draw          = draw,
                            MaterialIndex = updated ? 1 : 0,
                            BoundingBox   = bb
                        };
                        model.Add(mesh);
                    }

                    // Create an entity per layer
                    var layerEntity = new Entity($"Navigation group {currentId}");

                    // Add a new model component
                    var modelComponent = new ModelComponent(model);
                    layerEntity.Add(modelComponent);
                    modelComponent.Enabled = displayGroup.IsVisible;
                    ret.ModelComponents.Add(currentId, modelComponent);

                    ret.DebugEntity.AddChild(layerEntity);
                }
            }

            return(ret);
        }
Exemplo n.º 13
0
 /// <Docs>The item to add to the current collection.</Docs>
 /// <para>Adds an item to the current collection.</para>
 /// <remarks>To be added.</remarks>
 /// <exception cref="System.NotSupportedException">The current collection is read-only.</exception>
 /// <summary>
 /// Agrega una entrada
 /// </summary>
 /// <param name="item">Item.</param>
 public void Add(KeyValuePair <T, TVal> item)
 {
     Model.Add(item);
 }
Exemplo n.º 14
0
 /// <summary>
 /// Agrega una entrada
 /// </summary>
 /// <param name="key">Key.</param>
 /// <param name="value">Value.</param>
 public void Add(T key, TVal value)
 {
     Model.Add(key, value);
 }
Exemplo n.º 15
0
 public void Add()
 {
     ReadOnly = false;
     GoToEditControl();
     Model?.Add();
 }
Exemplo n.º 16
0
        public Model BuildComparisonObjects(IConnection sourceConnection, IConnection targetConnection)
        {
            SqlOption options = BuildOptions();

            OnComparisonStarted(EventArgs.Empty);

            var source = new Generate {ConnectionString = sourceConnection.ConnectionString, Options = options};

            source.OnProgress += args => OnFeedbackMessage(new FeedbackEventArgs
                                                               {
                                                                   Message = args.Message,
                                                                   ProgressPercent =
                                                                       args.Progress*(40/Generate.MaxValue)
                                                               });
            _source = source.Process();

            var target = new Generate {ConnectionString = targetConnection.ConnectionString, Options = options};
            target.OnProgress += args => OnFeedbackMessage(new FeedbackEventArgs
                                                               {
                                                                   Message = args.Message,
                                                                   ProgressPercent =
                                                                       40 + (args.Progress*(40/Generate.MaxValue))
                                                               });

            _target = target.Process();

            OnFeedbackMessage(new FeedbackEventArgs {Message = "Running comparison...", ProgressPercent = 90});
            _merged = Generate.Compare((Database) _target.Clone(null), _source);

            OnFeedbackMessage(new FeedbackEventArgs {Message = "Building Model...", ProgressPercent = 95});
            var model = new Model();

            _merged.Tables.ForEach(
                item => model.Add("Table", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Views.ForEach(
                item => model.Add("View", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Users.ForEach(
                item => model.Add("User", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.UserTypes.ForEach(
                item => model.Add("User Type", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.XmlSchemas.ForEach(
                item => model.Add("XML Schema", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Assemblies.ForEach(
                item =>
                model.Add("CLR Assemblie", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.CLRFunctions.ForEach(
                item =>
                model.Add("CLR Function", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.CLRProcedures.ForEach(
                item =>
                model.Add("CLR Procedure", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.DDLTriggers.ForEach(
                item =>
                model.Add("DDL Trigger", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Defaults.ForEach(
                item => model.Add("Default", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.ExtendedProperties.ForEach(
                item =>
                model.Add("Extended Property", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.FileGroups.ForEach(
                item =>
                model.Add("File Groups", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Functions.ForEach(
                item => model.Add("Functions", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.PartitionFunctions.ForEach(
                item =>
                model.Add("Partition Function", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.PartitionSchemes.ForEach(
                item =>
                model.Add("Partition Scheme", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Procedures.ForEach(
                item =>
                model.Add("Stored Procedure", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Roles.ForEach(
                item => model.Add("Role", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Schemas.ForEach(
                item => model.Add("Schema", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));
            _merged.Synonyms.ForEach(
                item => model.Add("Synonym", item.FullName, new Guid(item.Guid), item.Id, ResolveAction(item.Status)));

            OnFeedbackMessage(new FeedbackEventArgs {Message = "Comparison Complete", ProgressPercent = 100});
            OnComparisonCompleted(EventArgs.Empty);

            return model;
        }
Exemplo n.º 17
0
        public override void Run(string path)
        {
            // Compute the ring.

            Point3[] ring = new Point3[ringSteps];

            for (int ringStep = 0; ringStep < ringSteps; ++ringStep)
            {
                double theta = ringStep * 2 * Math.PI / ringSteps;

                ring[ringStep] = new Point3(
                    ringRadius * Math.Cos(theta) + pieRadius,
                    0,
                    ringRadius * Math.Sin(theta));
            }

            // Open the model.

            Model model = new Model();

            // Compute the pie.

            for (int pieStep = 0; pieStep < pieSteps; ++pieStep)
            {
                double theta0 = pieStep * 2 * Math.PI / pieSteps;
                double theta1 = (((pieStep + 1)) % pieSteps) * 2 * Math.PI / pieSteps;

                for (int ringStep = 0; ringStep < ringSteps; ++ringStep)
                {
                    IList <EdgePoint> corners = new List <EdgePoint>();

                    double x = ring[ringStep].X;
                    double y = ring[ringStep].Y;
                    double z = ring[ringStep].Z;

                    double xNext = ring[((ringStep + 1) % ringSteps)].X;
                    double yNext = ring[((ringStep + 1) % ringSteps)].Y;
                    double zNext = ring[((ringStep + 1) % ringSteps)].Z;

                    double xMod;
                    double yMod;
                    double zMod;

                    RingMod(
                        ringFreq, ringAmp, theta1,
                        x, y, z,
                        out xMod, out yMod, out zMod);

                    double x0 = xMod * Math.Cos(theta1) - yMod * Math.Sin(theta1);
                    double y0 = xMod * Math.Sin(theta1) + yMod * Math.Cos(theta1);
                    double z0 = zMod;

                    RingMod(
                        ringFreq, ringAmp, theta1,
                        xNext, yNext, zNext,
                        out xMod, out yMod, out zMod);

                    double x1 = xMod * Math.Cos(theta1) - yMod * Math.Sin(theta1);
                    double y1 = xMod * Math.Sin(theta1) + yMod * Math.Cos(theta1);
                    double z1 = zMod;

                    RingMod(
                        ringFreq, ringAmp, theta0,
                        xNext, yNext, zNext,
                        out xMod, out yMod, out zMod);

                    double x2 = xMod * Math.Cos(theta0) - yMod * Math.Sin(theta0);
                    double y2 = xMod * Math.Sin(theta0) + yMod * Math.Cos(theta0);
                    double z2 = zMod;

                    RingMod(
                        ringFreq, ringAmp, theta0,
                        x, y, z,
                        out xMod, out yMod, out zMod);

                    double x3 = xMod * Math.Cos(theta0) - yMod * Math.Sin(theta0);
                    double y3 = xMod * Math.Sin(theta0) + yMod * Math.Cos(theta0);
                    double z3 = zMod;

                    corners.Add(new EdgePoint(x1, y1, z1, true));
                    corners.Add(new EdgePoint(x2, y2, z2, true));
                    corners.Add(new EdgePoint(x3, y3, z3, true));

                    model.Add(corners);

                    corners.Clear();
                    corners.Add(new EdgePoint(x0, y0, z0, true));
                    corners.Add(new EdgePoint(x1, y1, z1, true));
                    corners.Add(new EdgePoint(x3, y3, z3, true));

                    model.Add(corners);
                }
            }

            model.WriteSketchUpFile(path + @"\PlainTorus.skp");
        }
Exemplo n.º 18
0
        public List<Exception> AddMetadata(string key, object value, Model.Document doc)
        {
            JProperty jprop;
            JsonSerializerSettings settings = new JsonSerializerSettings();
            List<Exception> errors = new List<Exception>();

            settings.Error += delegate(object sender, ErrorEventArgs args)
            {
                if (args.CurrentObject == args.ErrorContext.OriginalObject)
                    errors.Add(args.ErrorContext.Error);
            };

            if (errors.Count > 0)
                return errors;

            if (key.StartsWith("$"))
            {
                errors.Add(new FormatException("Metadata keys cannot begin with '$'."));
                return errors;
            }

            jprop = new JProperty(key, value);
            doc.Add(jprop);

            return null;
        }
Exemplo n.º 19
0
        public void AddCube(Cube c)
        {
            if ((selectedSide.Parent != null) && (selectedSide.Parent.Origin != null))
            {
                Cube copyC = new Cube();
                copyC.Initialize(c);

                Cube newCube = new Cube();

                newCube.Initialize(selectedSide.Parent.Origin);
                newCube.TransCube = new Cube();
                newCube.TransCube.Initialize(selectedSide.Parent.TransCube);
                double org = 0, now = 0;
                switch (selectedSide.maxState)
                {
                case "minY":
                    org = newCube.faces[0].MaxY();
                    now = selectedSide.Parent.faces[0].MaxY();

                    newCube.TransCube.Translate(0, -2, 0);
                    //copyC.TransCube.Translate(0, -2, 0);

                    if (org > now)
                    {
                        newCube.Translate(0, -2 - (org - now), 0);

                        //copyC.Translate(0, -2 - (org - now), 0);
                    }
                    else
                    {
                        newCube.Translate(0, -2 + (now - org), 0);
                        //copyC.Translate(0, -2 + (now - org), 0);
                    }


                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    //newCube.Initialize(copyC);

                    //find center

                    Vertex center = new Vertex();
                    center.x = 0; center.y = 0; center.z = 0;

                    //serendyp approxymations
                    double sumX = 0, sumY = 0, sumZ = 0;
                    for (int j = 0; j < 20; j++)
                    {
                        double fi = F_i(center, j);
                        sumX += newCube.vertices[j].x * fi;
                        sumY += newCube.vertices[j].y * fi;
                        sumZ += newCube.vertices[j].z * fi;
                    }
                    double x0 = sumX;
                    double y0 = sumY;
                    double z0 = sumZ;

                    MessageBox.Show("MinY (" + x0 + ", " + y0 + ", " + z0 + ")");

                    copyC.Translate(x0, y0, z0);
                    newCube.Initialize(copyC);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "minY");


                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);


                    Model.Add(newCube);
                    break;

                case "maxY":
                    org = newCube.faces[1].MinY();
                    now = selectedSide.Parent.faces[1].MinY();

                    newCube.TransCube.Translate(0, 2, 0);
                    //copyC.TransCube.Translate(0, 2, 0);

                    if (org < now)
                    {
                        newCube.Translate(0, 2 + (org - now), 0);
                        //copyC.Translate(0, 2 + (org - now), 0);
                    }
                    else
                    {
                        newCube.Translate(0, 2 - (org - now), 0);
                        //copyC.Translate(0, 2 - (org - now), 0);
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    center   = new Vertex();
                    center.x = 0; center.y = 0; center.z = 0;
                    sumX     = 0; sumY = 0; sumZ = 0;
                    for (int j = 0; j < 20; j++)
                    {
                        double fi = F_i(center, j);
                        sumX += newCube.vertices[j].x * fi;
                        sumY += newCube.vertices[j].y * fi;
                        sumZ += newCube.vertices[j].z * fi;
                    }
                    x0 = sumX;
                    y0 = sumY;
                    z0 = sumZ;

                    MessageBox.Show("MaxY (" + x0 + ", " + y0 + ", " + z0 + ")");

                    copyC.Translate(x0, y0, z0);
                    newCube.Initialize(copyC);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "maxY");


                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);



                    Model.Add(newCube);



                    break;

                case "minX":
                    org = newCube.faces[5].MaxX();
                    now = selectedSide.Parent.faces[5].MaxX();

                    newCube.TransCube.Translate(-2, 0, 0);
                    // copyC.TransCube.Translate(-2, 0, 0);

                    if (org > now)
                    {
                        newCube.Translate(-2 - (org - now), 0, 0);
                        //copyC.Translate(-2 - (org - now), 0, 0);
                    }
                    else
                    {
                        newCube.Translate(-2 + (now - org), 0, 0);
                        //copyC.Translate(-2 + (now - org), 0, 0);
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    center   = new Vertex();
                    center.x = 0; center.y = 0; center.z = 0;
                    sumX     = 0; sumY = 0; sumZ = 0;
                    for (int j = 0; j < 20; j++)
                    {
                        double fi = F_i(center, j);
                        sumX += newCube.vertices[j].x * fi;
                        sumY += newCube.vertices[j].y * fi;
                        sumZ += newCube.vertices[j].z * fi;
                    }
                    x0 = sumX;
                    y0 = sumY;
                    z0 = sumZ;

                    MessageBox.Show("MinX (" + x0 + ", " + y0 + ", " + z0 + ")");

                    copyC.Translate(x0, y0, z0);
                    newCube.Initialize(copyC);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "minX");
                    CheckAllFaces(1, 0, 0, 0, 0, 0, ref newCube);



                    Model.Add(newCube);
                    break;

                case "maxX":
                    org = newCube.faces[3].MinX();
                    now = selectedSide.Parent.faces[3].MinX();

                    newCube.TransCube.Translate(2, 0, 0);
                    //copyC.TransCube.Translate(2, 0, 0);

                    if (org < now)
                    {
                        newCube.Translate(2 + (org - now), 0, 0);
                        //copyC.Translate(2 + (org - now), 0, 0);
                    }
                    else
                    {
                        newCube.Translate(2 - (org - now), 0, 0);
                        //copyC.Translate(2 - (org - now), 0, 0);
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    center   = new Vertex();
                    center.x = 0; center.y = 0; center.z = 0;
                    sumX     = 0; sumY = 0; sumZ = 0;
                    for (int j = 0; j < 20; j++)
                    {
                        double fi = F_i(center, j);
                        sumX += newCube.vertices[j].x * fi;
                        sumY += newCube.vertices[j].y * fi;
                        sumZ += newCube.vertices[j].z * fi;
                    }
                    x0 = sumX;
                    y0 = sumY;
                    z0 = sumZ;

                    MessageBox.Show("MaxX (" + x0 + ", " + y0 + ", " + z0 + ")");

                    copyC.Translate(x0, y0, z0);
                    newCube.Initialize(copyC);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "maxX");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);



                    Model.Add(newCube);
                    break;

                case "minZ":
                    org = newCube.faces[4].MaxZ();
                    now = selectedSide.Parent.faces[4].MaxZ();

                    newCube.TransCube.Translate(0, 0, -2);
                    //copyC.TransCube.Translate(0, 0, -2);

                    if (org > now)
                    {
                        newCube.Translate(0, 0, -2 - (org - now));
                        //copyC.Translate(0, 0, -2 - (org - now));
                    }
                    else
                    {
                        newCube.Translate(0, 0, -2 + (now - org));
                        //copyC.Translate(0, 0, -2 + (now - org));
                    }


                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    center   = new Vertex();
                    center.x = 0; center.y = 0; center.z = 0;
                    sumX     = 0; sumY = 0; sumZ = 0;
                    for (int j = 0; j < 20; j++)
                    {
                        double fi = F_i(center, j);
                        sumX += newCube.vertices[j].x * fi;
                        sumY += newCube.vertices[j].y * fi;
                        sumZ += newCube.vertices[j].z * fi;
                    }
                    x0 = sumX;
                    y0 = sumY;
                    z0 = sumZ;

                    MessageBox.Show("MinZ (" + x0 + ", " + y0 + ", " + z0 + ")");

                    copyC.Translate(x0, y0, z0);
                    newCube.Initialize(copyC);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "minZ");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);



                    Model.Add(newCube);
                    break;

                case "maxZ":
                    org = newCube.faces[2].MinZ();
                    now = selectedSide.Parent.faces[2].MinZ();

                    newCube.TransCube.Translate(0, 0, 2);
                    //copyC.TransCube.Translate(0, 0, 2);

                    if (org < now)
                    {
                        newCube.Translate(0, 0, 2 + (org - now));
                        //copyC.Translate(0, 0, 2 + (org - now));
                    }
                    else
                    {
                        newCube.Translate(0, 0, 2 - (org - now));
                        //copyC.Translate(0, 0, 2 - (org - now));
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    center   = new Vertex();
                    center.x = 0; center.y = 0; center.z = 0;
                    sumX     = 0; sumY = 0; sumZ = 0;
                    for (int j = 0; j < 20; j++)
                    {
                        double fi = F_i(center, j);
                        sumX += newCube.vertices[j].x * fi;
                        sumY += newCube.vertices[j].y * fi;
                        sumZ += newCube.vertices[j].z * fi;
                    }
                    x0 = sumX;
                    y0 = sumY;
                    z0 = sumZ;

                    MessageBox.Show("MaxZ (" + x0 + ", " + y0 + ", " + z0 + ")");

                    copyC.Translate(x0, y0, z0);
                    newCube.Initialize(copyC);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "maxZ");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);



                    Model.Add(newCube);
                    break;
                }


                DevideCurveCube(Model.Count - 1, ref newCube);
            }
            else
            {
                IsAddingCube = false;
            }
            IsAddingCube           = false;
            selectedSide.IsPointed = false;
        }
Exemplo n.º 20
0
 public IResponse Add(IPieceAgent agent)
 {
     return(Model.Add(agent.Model));
 }
Exemplo n.º 21
0
        public void Run()
        {
            Console.WriteLine("Williams_12_1_FoodManufacture");

            const int     numberRawMaterials = 5;
            const int     numberMonths       = 6;
            List <string> rawMaterials       = new List <string> {
                "Veg1", "Veg2", "Oil1", "Oil2", "Oil3"
            };
            List <string> months = new List <string> {
                "Jan", "Feb", "Mar", "Apr", "May", "Jun"
            };

            double[,] rawMaterialCost = new double[numberRawMaterials, numberMonths];
            // Veg1
            rawMaterialCost[0, 0] = 110.0; // Jan
            rawMaterialCost[0, 1] = 130.0; // Feb
            rawMaterialCost[0, 2] = 110.0; // Mar
            rawMaterialCost[0, 3] = 120.0; // Apr
            rawMaterialCost[0, 4] = 100.0; // May
            rawMaterialCost[0, 5] = 90.0;  // Jun
            // Veg2
            rawMaterialCost[1, 0] = 120.0; // Jan
            rawMaterialCost[1, 1] = 130.0; // Feb
            rawMaterialCost[1, 2] = 140.0; // Mar
            rawMaterialCost[1, 3] = 110.0; // Apr
            rawMaterialCost[1, 4] = 120.0; // May
            rawMaterialCost[1, 5] = 100.0; // Jun
            // Oil1
            rawMaterialCost[2, 0] = 130.0; // Jan
            rawMaterialCost[2, 1] = 110.0; // Feb
            rawMaterialCost[2, 2] = 130.0; // Mar
            rawMaterialCost[2, 3] = 120.0; // Apr
            rawMaterialCost[2, 4] = 150.0; // May
            rawMaterialCost[2, 5] = 140.0; // Jun
            // Oil2
            rawMaterialCost[3, 0] = 110.0; // Jan
            rawMaterialCost[3, 1] = 90.0;  // Feb
            rawMaterialCost[3, 2] = 100.0; // Mar
            rawMaterialCost[3, 3] = 120.0; // Apr
            rawMaterialCost[3, 4] = 110.0; // May
            rawMaterialCost[3, 5] = 80.0;  // Jun
            // Oil2
            rawMaterialCost[4, 0] = 115.0; // Jan
            rawMaterialCost[4, 1] = 115.0; // Feb
            rawMaterialCost[4, 2] = 95.0;  // Mar
            rawMaterialCost[4, 3] = 125.0; // Apr
            rawMaterialCost[4, 4] = 105.0; // May
            rawMaterialCost[4, 5] = 135.0; // Jun

            double[] hardness = new double[numberRawMaterials] {
                8.8, 6.1, 2.0, 4.2, 5.0
            };
            double productValue = 150.0;
            double minHardness  = 3.0;
            double maxHardness  = 6.0;

            bool[] isVeg = new bool[numberRawMaterials] {
                true, true, false, false, false
            };
            bool[] isOil = new bool[numberRawMaterials] {
                false, false, true, true, true
            };
            double maxVegRefineCapacity = 200.0; // tonnes per month
            double maxOilRefineCapacity = 250.0; // tonnes per month

            double[] maxStorageCapacity = new double[numberRawMaterials] {
                1000.0, 1000.0, 1000.0, 1000.0, 1000.0
            };                                                                                                       // tonnes
            double[] storageCosts = new double[numberRawMaterials] {
                5.0, 5.0, 5.0, 5.0, 5.0
            };                                                                                  // per tonne per month
            double[] initialStock = new double[numberRawMaterials] {
                500.0, 500.0, 500.0, 500.0, 500.0
            };                                                                                            // tonnes
            double[] finalStock = new double[numberRawMaterials] {
                500.0, 500.0, 500.0, 500.0, 500.0
            };                                                                                          // tonnes

            Model  model  = new Model();
            Solver solver = new Solver(model, typeof(OsiClpSolverInterface));

            // Create the main decision variables
            Variable[] productionVar = new Variable[numberMonths];
            Variable[,] buyVar   = new Variable[numberRawMaterials, numberMonths];
            Variable[,] useVar   = new Variable[numberRawMaterials, numberMonths];
            Variable[,] storeVar = new Variable[numberRawMaterials, numberMonths];
            int i, j;

            for (j = 0; j < numberMonths; j++)
            {
                string name = "Produce_" + months[j];
                productionVar[j] = new Variable(name, 0.0, maxVegRefineCapacity + maxOilRefineCapacity, VariableType.Continuous);
                for (i = 0; i < numberRawMaterials; i++)
                {
                    double maxUse = 0.0;
                    if (isVeg[i])
                    {
                        maxUse = maxVegRefineCapacity;
                    }
                    if (isOil[i])
                    {
                        maxUse = maxOilRefineCapacity;
                    }
                    double maxBuy   = maxUse + maxStorageCapacity[i];
                    double maxStore = maxStorageCapacity[i];
                    name           = "Buy_" + rawMaterials[i] + "_" + months[j];
                    buyVar[i, j]   = new Variable(name, 0.0, maxBuy, VariableType.Continuous);
                    name           = "Use_" + rawMaterials[i] + "_" + months[j];
                    useVar[i, j]   = new Variable(name, 0.0, maxUse, VariableType.Continuous);
                    name           = "Store_" + rawMaterials[i] + "_" + months[j];
                    storeVar[i, j] = new Variable(name, 0.0, maxStore, VariableType.Continuous);
                }
            }

            // Limit the total amount of each type of raw material that can be refined each month
            for (j = 0; j < numberMonths; j++)
            {
                Expression totalVegUseInMonth = new Expression();
                Expression totalOilUseInMonth = new Expression();
                for (i = 0; i < numberRawMaterials; i++)
                {
                    if (isVeg[i])
                    {
                        totalVegUseInMonth.Add(useVar[i, j]);
                    }
                    if (isOil[i])
                    {
                        totalOilUseInMonth.Add(useVar[i, j]);
                    }
                }
                Constraint limitVeg = (totalVegUseInMonth <= maxVegRefineCapacity);
                limitVeg.Name = "LimitVegCt_" + months[j];
                Constraint limitOil = (totalVegUseInMonth <= maxVegRefineCapacity);
                limitOil.Name = "LimitOilCt_" + months[j];
                model.Add(limitVeg);
                model.Add(limitOil);
            }

            // Limit the final product hardness to be within the specified range
            for (j = 0; j < numberMonths; j++)
            {
                Expression hardnessInMonth = new Expression();
                for (i = 0; i < numberRawMaterials; i++)
                {
                    hardnessInMonth.Add(hardness[i], useVar[i, j]);
                }
                Constraint maxHardnessCt = (hardnessInMonth - (maxHardness * productionVar[j]) <= 0.0);
                maxHardnessCt.Name = "MaxHardnessCt_" + months[j];
                Constraint minHardnessCt = (hardnessInMonth - (minHardness * productionVar[j]) >= 0.0);
                minHardnessCt.Name = "MinHardnessCt_" + months[j];
                model.Add(maxHardnessCt);
                model.Add(minHardnessCt);
            }

            // Fix the final product quantity to be the sum of the raw materials used for each month
            for (j = 0; j < numberMonths; j++)
            {
                Expression totalRawMaterialUsedInMonth = new Expression();
                for (i = 0; i < numberRawMaterials; i++)
                {
                    totalRawMaterialUsedInMonth.Add(useVar[i, j]);
                }
                Constraint productionBalanceCt = (totalRawMaterialUsedInMonth - productionVar[j] == 0.0);
                productionBalanceCt.Name = "ProductionBalanceCt_" + months[j];
                model.Add(productionBalanceCt);
            }

            // Fix the inventory balance for each product and each month.
            for (i = 0; i < numberRawMaterials; i++)
            {
                // Note we start here at month 1 as we refer back to the previous month
                // and we handle the starting and ending stock levels separately below
                for (j = 1; j < numberMonths; j++)
                {
                    Constraint inventoryBalanceCt = (storeVar[i, j - 1] + buyVar[i, j] - useVar[i, j] - storeVar[i, j] == 0.0);
                    inventoryBalanceCt.Name = "InventoryBalanceCt_" + rawMaterials[i] + "_" + months[j];
                    model.Add(inventoryBalanceCt);
                }
                // Here we fix the initial stock level
                Constraint initialInventoryBalanceCt = (initialStock[i] + buyVar[i, 0] - useVar[i, 0] - storeVar[i, 0] == 0.0);
                initialInventoryBalanceCt.Name = "InitialInventoryBalanceCt_" + rawMaterials[i] + "_" + months[0];
                model.Add(initialInventoryBalanceCt);
                // Here we fix the final stock level
                Constraint finalInventoryBalanceCt = (storeVar[i, (numberMonths - 1)] == finalStock[i]);
                finalInventoryBalanceCt.Name = "FinalInventoryBalanceCt_" + rawMaterials[i];
                model.Add(finalInventoryBalanceCt);
            }

            // Find the total costs of raw material and inventory storage
            // and the total value of all the products
            Expression totalRawMaterialCost = new Expression();
            Expression totalStorageCost     = new Expression();
            Expression totalProductValue    = new Expression();

            for (j = 0; j < numberMonths; j++)
            {
                totalProductValue.Add(productValue, productionVar[j]);
                for (i = 0; i < numberRawMaterials; i++)
                {
                    totalRawMaterialCost.Add(rawMaterialCost[i, j], buyVar[i, j]);
                    totalStorageCost.Add(storageCosts[i], storeVar[i, j]);
                }
            }

            Objective obj = totalProductValue - totalRawMaterialCost - totalStorageCost;

            model.Objective      = obj;
            model.ObjectiveSense = ObjectiveSense.Maximise;
            model.Export("Food.sonnet");
            solver.Solve();

            if (solver.IsProvenOptimal)
            {
                Console.WriteLine("----------------------------------------------------------------------------------------------");
                for (i = 0; i < numberRawMaterials; i++)
                {
                    Console.Write("\t\t" + rawMaterials[i]);
                }
                Console.Write("\n");
                Console.WriteLine("----------------------------------------------------------------------------------------------");
                // Now output the solution that we have found
                for (j = 0; j < numberMonths; j++)
                {
                    Console.Write(months[j] + "\tBuy ");
                    for (i = 0; i < numberRawMaterials; i++)
                    {
                        Console.Write("\t" + buyVar[i, j].Value.ToString("F3") + "\t");
                    }
                    Console.Write("\n");
                    Console.Write(months[j] + "\tUse ");
                    for (i = 0; i < numberRawMaterials; i++)
                    {
                        Console.Write("\t" + useVar[i, j].Value.ToString("F3") + "\t");
                    }
                    Console.Write("\n");
                    Console.Write(months[j] + "\tStore");
                    for (i = 0; i < numberRawMaterials; i++)
                    {
                        Console.Write("\t" + useVar[i, j].Value.ToString("F3") + "\t");
                    }
                    Console.Write("\n");
                    Console.WriteLine(months[j] + "\tProduct\t\t\t\t\t\t\t\t\t\t" + productionVar[j].Value.ToString("F3"));
                    Console.WriteLine("----------------------------------------------------------------------------------------------");
                }
            }
        }
Exemplo n.º 22
0
        void AddCube1(Cube newCube)
        {
            if ((selectedSide.Parent != null) && (selectedSide.Parent.Origin != null))
            {
                //Cube newCube = new Cube();

                //newCube.Initialize(selectedSide.Parent.Origin);
                newCube.Origin = new Cube();
                newCube.Origin.Initialize(selectedSide.Parent.Origin);
                newCube.TransCube = new Cube();
                newCube.TransCube.Initialize(selectedSide.Parent.TransCube);
                double org = 0, now = 0;
                switch (selectedSide.maxState)
                {
                case "minY":
                    org = newCube.faces[0].MaxY();
                    now = selectedSide.Parent.faces[0].MaxY();

                    newCube.TransCube.Translate(0, -2, 0);

                    if (org > now)
                    {
                        newCube.Translate(0, -2 - (org - now), 0);
                    }
                    else
                    {
                        newCube.Translate(0, -2 + (now - org), 0);
                    }


                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "minY");


                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);


                    Model.Add(newCube);
                    break;

                case "maxY":
                    org = newCube.faces[1].MinY();
                    now = selectedSide.Parent.faces[1].MinY();

                    newCube.TransCube.Translate(0, 2, 0);

                    if (org < now)
                    {
                        newCube.Translate(0, 2 + (org - now), 0);
                    }
                    else
                    {
                        newCube.Translate(0, 2 - (org - now), 0);
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "maxY");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);

                    Model.Add(newCube);

                    break;

                case "minX":
                    org = newCube.faces[5].MaxX();
                    now = selectedSide.Parent.faces[5].MaxX();

                    newCube.TransCube.Translate(-2, 0, 0);

                    if (org > now)
                    {
                        newCube.Translate(-2 - (org - now), 0, 0);
                    }
                    else
                    {
                        newCube.Translate(-2 + (now - org), 0, 0);
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "minX");
                    CheckAllFaces(1, 0, 0, 0, 0, 0, ref newCube);


                    Model.Add(newCube);
                    break;

                case "maxX":
                    org = newCube.faces[3].MinX();
                    now = selectedSide.Parent.faces[3].MinX();

                    newCube.TransCube.Translate(2, 0, 0);

                    if (org < now)
                    {
                        newCube.Translate(2 + (org - now), 0, 0);
                    }
                    else
                    {
                        newCube.Translate(2 - (org - now), 0, 0);
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "maxX");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);

                    Model.Add(newCube);
                    break;

                case "minZ":
                    org = newCube.faces[4].MaxZ();
                    now = selectedSide.Parent.faces[4].MaxZ();

                    newCube.TransCube.Translate(0, 0, -2);

                    if (org > now)
                    {
                        newCube.Translate(0, 0, -2 - (org - now));
                    }
                    else
                    {
                        newCube.Translate(0, 0, -2 + (now - org));
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "minZ");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);

                    Model.Add(newCube);
                    break;

                case "maxZ":
                    org = newCube.faces[2].MinZ();
                    now = selectedSide.Parent.faces[2].MinZ();

                    newCube.TransCube.Translate(0, 0, 2);

                    if (org < now)
                    {
                        newCube.Translate(0, 0, 2 + (org - now));
                    }
                    else
                    {
                        newCube.Translate(0, 0, 2 - (org - now));
                    }

                    newCube.Origin = new Cube();
                    newCube.Origin.Initialize(newCube);

                    InitializeFace(ref newCube, ref selectedSide.Parent, "maxZ");
                    CheckAllFaces(0, 0, 0, 0, 0, 0, ref newCube);

                    Model.Add(newCube);
                    break;
                }
                DevideCurveCube(Model.Count - 1, ref newCube);
            }
            else
            {
                IsAddingCube = false;
            }
            IsAddingCube           = false;
            selectedSide.IsPointed = false;
        }
Exemplo n.º 23
0
        private static void BuildClassTestModel()
        {
            EntityInterface iPerson = GetInterface();
            EntityClass parent = new EntityClass();
            parent.Name = "Pai";
            EntityClass category = new EntityClass();
            category.Name = "Category";
            category.Visibility = "public";
            category.Interfaces.Add(iPerson);
            category.Parent = parent;

            EntityField field = new EntityField();
            field.Name = "Id";
            field.Visibility = "protected";
            field.IsPrimaryKey = true;
            field.Type = new Int();
            category.Fields.Add(field);

            field = new EntityField();
            field.Name = "Description";
            field.IsRequired = true;
            field.MaxSize = 500;
            field.Type = new Loki.DataRepresentation.IntrinsicEntities.String();
            category.Fields.Add(field);
            category.IsAbstract = true;
            category.Persistable = true;
            category.Visibility = "protected";

            EntityMethod init = new EntityMethod();
            init.Name = "Init";

            category.Methods.Add(init);

            Model list = new Model();
            list.Add(category);
            classes.Model = list;
        }
Exemplo n.º 24
0
 public void Add(MenuItemBase item)
 {
     Model.Add(item);
 }
Exemplo n.º 25
0
        private static unsafe void ProcessMaterial(List <BatchingChunk> chunks, MaterialInstance material, Model prefabModel, HashSet <Entity> unbatched = null)
        {
            //actually create the mesh
            List <VertexPositionNormalTextureTangent> vertsNT = null;
            List <VertexPositionNormalColor>          vertsNC = null;
            List <uint> indiciesList = new List <uint>();
            BoundingBox bb           = new BoundingBox(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity),
                                                       new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity));
            uint indexOffset = 0;

            for (int i = 0; i < chunks.Count; i++)
            {
                BatchingChunk chunk = chunks[i];
                if (unbatched != null && unbatched.Contains(chunk.Entity))
                {
                    continue;                                                        // don't try batching other things in this entity if some failed
                }
                if (chunk.Entity != null)
                {
                    chunk.Entity.Transform.UpdateLocalMatrix();
                    chunk.Entity.Transform.SlimUpdateWorldMatrix();
                }
                Matrix worldMatrix = chunk.Entity == null ? (chunk.Transform ?? Matrix.Identity) : chunk.Entity.Transform.WorldMatrix;
                Matrix rot;
                if (worldMatrix != Matrix.Identity)
                {
                    worldMatrix.GetRotationMatrix(out rot);
                }
                else
                {
                    rot = Matrix.Identity;
                }
                for (int j = 0; j < chunk.Model.Meshes.Count; j++)
                {
                    Mesh modelMesh = chunk.Model.Meshes[j];
                    //process only right material
                    if (modelMesh.MaterialIndex == chunk.MaterialIndex)
                    {
                        Vector3[] positions = null, normals = null;
                        Vector4[] tangents  = null;
                        Vector2[] uvs       = null;
                        Color4[]  colors    = null;

                        //vertexes
                        if (CachedModelData.TryGet(modelMesh, out var information))
                        {
                            // clone positions and normals, since they may change
                            positions = (Vector3[])information.positions.Clone();
                            normals   = (Vector3[])information.normals.Clone();
                            tangents  = information.tangents;
                            uvs       = information.uvs;
                            colors    = information.colors;
                            for (int k = 0; k < information.indicies.Length; k++)
                            {
                                indiciesList.Add(information.indicies[k] + indexOffset);
                            }
                        }
                        else if (modelMesh.Draw is StagedMeshDraw)
                        {
                            StagedMeshDraw smd = modelMesh.Draw as StagedMeshDraw;

                            object verts = smd.Verticies;

                            if (verts is VertexPositionNormalColor[])
                            {
                                VertexPositionNormalColor[] vpnc = verts as VertexPositionNormalColor[];
                                positions = new Vector3[vpnc.Length];
                                normals   = new Vector3[vpnc.Length];
                                colors    = new Color4[vpnc.Length];
                                for (int k = 0; k < vpnc.Length; k++)
                                {
                                    positions[k] = vpnc[k].Position;
                                    normals[k]   = vpnc[k].Normal;
                                    colors[k]    = vpnc[k].Color;
                                }
                            }
                            else if (verts is VertexPositionNormalTexture[])
                            {
                                VertexPositionNormalTexture[] vpnc = verts as VertexPositionNormalTexture[];
                                positions = new Vector3[vpnc.Length];
                                normals   = new Vector3[vpnc.Length];
                                uvs       = new Vector2[vpnc.Length];
                                for (int k = 0; k < vpnc.Length; k++)
                                {
                                    positions[k] = vpnc[k].Position;
                                    normals[k]   = vpnc[k].Normal;
                                    uvs[k]       = vpnc[k].TextureCoordinate;
                                }
                            }
                            else if (verts is VertexPositionNormalTextureTangent[])
                            {
                                VertexPositionNormalTextureTangent[] vpnc = verts as VertexPositionNormalTextureTangent[];
                                positions = new Vector3[vpnc.Length];
                                normals   = new Vector3[vpnc.Length];
                                uvs       = new Vector2[vpnc.Length];
                                tangents  = new Vector4[vpnc.Length];
                                for (int k = 0; k < vpnc.Length; k++)
                                {
                                    positions[k] = vpnc[k].Position;
                                    normals[k]   = vpnc[k].Normal;
                                    uvs[k]       = vpnc[k].TextureCoordinate;
                                    tangents[k]  = vpnc[k].Tangent;
                                }
                            }
                            else
                            {
                                // unsupported StagedMeshDraw
                                if (unbatched != null)
                                {
                                    unbatched.Add(chunk.Entity);
                                }
                                continue;
                            }

                            // take care of indicies
                            for (int k = 0; k < smd.Indicies.Length; k++)
                            {
                                indiciesList.Add(smd.Indicies[k] + indexOffset);
                            }

                            // cache this for later
                            CachedModelData.Add(modelMesh,
                                                new CachedData()
                            {
                                colors    = colors,
                                indicies  = smd.Indicies,
                                normals   = (Vector3[])normals.Clone(),
                                positions = (Vector3[])positions.Clone(),
                                tangents  = tangents,
                                uvs       = uvs
                            }
                                                );
                        }
                        else
                        {
                            Xenko.Graphics.Buffer buf  = modelMesh.Draw?.VertexBuffers[0].Buffer;
                            Xenko.Graphics.Buffer ibuf = modelMesh.Draw?.IndexBuffer.Buffer;
                            if (buf == null || buf.VertIndexData == null ||
                                ibuf == null || ibuf.VertIndexData == null)
                            {
                                if (unbatched != null)
                                {
                                    unbatched.Add(chunk.Entity);
                                }
                                continue;
                            }

                            if (UnpackRawVertData(buf.VertIndexData, modelMesh.Draw.VertexBuffers[0].Declaration,
                                                  out positions, out normals, out uvs, out colors, out tangents) == false)
                            {
                                if (unbatched != null)
                                {
                                    unbatched.Add(chunk.Entity);
                                }
                                continue;
                            }

                            CachedData cmd = new CachedData()
                            {
                                colors    = colors,
                                positions = (Vector3[])positions.Clone(),
                                normals   = (Vector3[])normals.Clone(),
                                uvs       = uvs,
                                tangents  = tangents
                            };

                            // indicies
                            fixed(byte *pdst = ibuf.VertIndexData)
                            {
                                if (modelMesh.Draw.IndexBuffer.Is32Bit)
                                {
                                    var dst = (uint *)pdst;

                                    int numIndices = ibuf.VertIndexData.Length / sizeof(uint);
                                    cmd.indicies = new uint[numIndices];
                                    for (var k = 0; k < numIndices; k++)
                                    {
                                        // Offset indices
                                        cmd.indicies[k] = dst[k];
                                        indiciesList.Add(dst[k] + indexOffset);
                                    }
                                }
                                else
                                {
                                    var dst = (ushort *)pdst;

                                    int numIndices = ibuf.VertIndexData.Length / sizeof(ushort);
                                    cmd.indicies = new uint[numIndices];
                                    for (var k = 0; k < numIndices; k++)
                                    {
                                        // Offset indices
                                        cmd.indicies[k] = dst[k];
                                        indiciesList.Add(dst[k] + indexOffset);
                                    }
                                }
                            }

                            CachedModelData.Add(modelMesh, cmd);
                        }

                        // what kind of structure will we be making, if we haven't picked one already?
                        if (vertsNT == null && vertsNC == null)
                        {
                            if (uvs != null)
                            {
                                vertsNT = new List <VertexPositionNormalTextureTangent>(positions.Length);
                            }
                            else
                            {
                                vertsNC = new List <VertexPositionNormalColor>(positions.Length);
                            }
                        }

                        // bounding box/finish list
                        bool needmatrix = worldMatrix != Matrix.Identity;
                        for (int k = 0; k < positions.Length; k++)
                        {
                            if (needmatrix)
                            {
                                Vector3.Transform(ref positions[k], ref worldMatrix, out positions[k]);

                                if (normals != null)
                                {
                                    Vector3.TransformNormal(ref normals[k], ref rot, out normals[k]);
                                }
                            }

                            // update bounding box?
                            Vector3 pos = positions[k];
                            if (pos.X > bb.Maximum.X)
                            {
                                bb.Maximum.X = pos.X;
                            }
                            if (pos.Y > bb.Maximum.Y)
                            {
                                bb.Maximum.Y = pos.Y;
                            }
                            if (pos.Z > bb.Maximum.Z)
                            {
                                bb.Maximum.Z = pos.Z;
                            }
                            if (pos.X < bb.Minimum.X)
                            {
                                bb.Minimum.X = pos.X;
                            }
                            if (pos.Y < bb.Minimum.Y)
                            {
                                bb.Minimum.Y = pos.Y;
                            }
                            if (pos.Z < bb.Minimum.Z)
                            {
                                bb.Minimum.Z = pos.Z;
                            }

                            if (vertsNT != null)
                            {
                                vertsNT.Add(new VertexPositionNormalTextureTangent
                                {
                                    Position          = positions[k],
                                    Normal            = normals != null ? normals[k] : Vector3.UnitY,
                                    TextureCoordinate = uvs[k],
                                    Tangent           = tangents != null ? tangents[k] : Vector4.UnitW
                                });
                            }
                            else
                            {
                                vertsNC.Add(new VertexPositionNormalColor
                                {
                                    Position = positions[k],
                                    Normal   = normals != null ? normals[k] : Vector3.UnitY,
                                    Color    = colors != null ? colors[k] : Color4.White
                                });
                            }
                        }

                        indexOffset += (uint)positions.Length;
                    }
                }
            }

            if (indiciesList.Count <= 0)
            {
                return;
            }

            uint[] indicies = indiciesList.ToArray();

            // make stagedmesh with verts
            StagedMeshDraw md;

            if (vertsNT != null)
            {
                var vertsNTa = vertsNT.ToArray();
                md = StagedMeshDraw.MakeStagedMeshDraw <VertexPositionNormalTextureTangent>(ref indicies, ref vertsNTa, VertexPositionNormalTextureTangent.Layout);
            }
            else if (vertsNC != null)
            {
                var vertsNCa = vertsNC.ToArray();
                md = StagedMeshDraw.MakeStagedMeshDraw <VertexPositionNormalColor>(ref indicies, ref vertsNCa, VertexPositionNormalColor.Layout);
            }
            else
            {
                return;
            }

            Mesh m = new Mesh
            {
                Draw          = md,
                BoundingBox   = bb,
                MaterialIndex = prefabModel.Materials.Count
            };

            prefabModel.Add(m);
            prefabModel.Add(material);
        }
        public override IQuestion Generate(Random random)
        {
            var greekLetters          = new string[] { "\\gamma", "\\epsilon", "\\zeta", "\\eta", "\\theta", "\\iota", "\\kappa", "\\mu", "\\nu", "\\xi", "\\rho", "\\sigma" };
            var reorderedGreekLetters = ReorderRandomly <string>(random, greekLetters);

            var model = new Model();

            model.Add("gl1", reorderedGreekLetters[0]);
            model.Add("gl2", reorderedGreekLetters[1]);
            model.Add("gl3", reorderedGreekLetters[2]);
            model.Add("gl4", reorderedGreekLetters[3]);
            model.Add("gl5", reorderedGreekLetters[4]);
            model.Add("gl6", reorderedGreekLetters[5]);
            model.Add("gl7", reorderedGreekLetters[6]);
            model.Add("gl8", reorderedGreekLetters[7]);
            model.Add("gl9", reorderedGreekLetters[8]);
            model.Add("gl10", reorderedGreekLetters[9]);
            model.Add("gl11", reorderedGreekLetters[10]);
            model.Add("gl12", reorderedGreekLetters[11]);

            return(Generate(model));
        }
Exemplo n.º 27
0
 public void Add()
 {
     NormalChartSeries[0].Values = model.Add();
 }
 private void MapArguments(EasyNetQ.Management.Client.Model.Arguments arguments, Model.Arguments modelArguments)
 {
     foreach (var argument in arguments)
         modelArguments.Add(argument.Key, argument.Value);
 }
Exemplo n.º 29
0
 public OrdersScheme(byte messageId)
     : base(messageId)
 {
     Model.Add(typeof(Request <Order>), true)
     .AddRequired(nameof(Request <Order> .Id));
 }
 public void CommandAdd_Exec(object args)
 {
     Model.Add();
 }
 private void Apply(RoomTypeAdded evt)
 {
     Model.Add(new RoomTypeItem(evt.TypeId, evt.Name, evt.Description));
 }
Exemplo n.º 32
0
        public void Generate(IServiceRegistry services, Model model)
        {
            if (model == null) throw new ArgumentNullException(nameof(model));

            var needsTempDevice = false;
            var graphicsDevice = services?.GetSafeServiceAs<IGraphicsDeviceService>().GraphicsDevice;
            if (graphicsDevice == null)
            {
                graphicsDevice = GraphicsDevice.New();
                needsTempDevice = true;
            }

            var data = CreatePrimitiveMeshData();

            if (data.Vertices.Length == 0)
            {
                throw new InvalidOperationException("Invalid GeometricPrimitive [{0}]. Expecting non-zero Vertices array");
            }

            if (LocalOffset != Vector3.Zero)
            {
                for (var index = 0; index < data.Vertices.Length; index++)
                {
                    data.Vertices[index].Position += LocalOffset;
                }
            }

            //Scale if necessary
            if (Scale != Vector3.One)
            {
                var inverseMatrix = Matrix.Scaling(Scale);
                inverseMatrix.Invert();
                for (var index = 0; index < data.Vertices.Length; index++)
                {
                    data.Vertices[index].Position *= Scale;
                    Vector3.TransformCoordinate(ref data.Vertices[index].Normal, ref inverseMatrix, out data.Vertices[index].Normal);
                }
            }

            var boundingBox = BoundingBox.Empty;
            for (int i = 0; i < data.Vertices.Length; i++)
                BoundingBox.Merge(ref boundingBox, ref data.Vertices[i].Position, out boundingBox);

            BoundingSphere boundingSphere;
            unsafe
            {
                fixed (void* verticesPtr = data.Vertices)
                    BoundingSphere.FromPoints((IntPtr)verticesPtr, 0, data.Vertices.Length, VertexPositionNormalTexture.Size, out boundingSphere);
            }

            var originalLayout = data.Vertices[0].GetLayout();

            // Generate Tangent/BiNormal vectors
            var resultWithTangentBiNormal = VertexHelper.GenerateTangentBinormal(originalLayout, data.Vertices, data.Indices);

            // Generate Multitexcoords
            var result = VertexHelper.GenerateMultiTextureCoordinates(resultWithTangentBiNormal);

            var meshDraw = new MeshDraw();

            var layout = result.Layout;
            var vertexBuffer = result.VertexBuffer;
            var indices = data.Indices;

            if (indices.Length < 0xFFFF)
            {
                var indicesShort = new ushort[indices.Length];
                for (int i = 0; i < indicesShort.Length; i++)
                {
                    indicesShort[i] = (ushort)indices[i];
                }
                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indicesShort).RecreateWith(indicesShort), false, indices.Length);
                if (needsTempDevice)
                {
                    var indexData = BufferData.New(BufferFlags.IndexBuffer, indicesShort);
                    meshDraw.IndexBuffer = new IndexBufferBinding(indexData.ToSerializableVersion(), false, indices.Length);
                }
            }
            else
            {
                if (graphicsDevice.Features.CurrentProfile <= GraphicsProfile.Level_9_3)
                {
                    throw new InvalidOperationException("Cannot generate more than 65535 indices on feature level HW <= 9.3");
                }

                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices).RecreateWith(indices), true, indices.Length);
                if (needsTempDevice)
                {
                    var indexData = BufferData.New(BufferFlags.IndexBuffer, indices);
                    meshDraw.IndexBuffer = new IndexBufferBinding(indexData.ToSerializableVersion(), true, indices.Length);
                }
            }

            meshDraw.VertexBuffers = new[] { new VertexBufferBinding(Buffer.New(graphicsDevice, vertexBuffer, BufferFlags.VertexBuffer).RecreateWith(vertexBuffer), layout, data.Vertices.Length) };
            if (needsTempDevice)
            {
                var vertexData = BufferData.New(BufferFlags.VertexBuffer, vertexBuffer);
                meshDraw.VertexBuffers = new[] { new VertexBufferBinding(vertexData.ToSerializableVersion(), layout, data.Vertices.Length) };
            }

            meshDraw.DrawCount = indices.Length;
            meshDraw.PrimitiveType = PrimitiveType.TriangleList;

            var mesh = new Mesh { Draw = meshDraw, BoundingBox = boundingBox, BoundingSphere = boundingSphere };

            model.BoundingBox = boundingBox;
            model.BoundingSphere = boundingSphere;
            model.Add(mesh);

            if (MaterialInstance?.Material != null)
            {
                model.Materials.Add(MaterialInstance);
            }

            if (needsTempDevice)
            {
                graphicsDevice.Dispose();
            }
        }
Exemplo n.º 33
0
        public static Entity Read(Game game, string name)
        {
            var zip      = new ZipArchive(VirtualFileSystem.OpenStream($"/cache/{name}.zip", VirtualFileMode.Open, VirtualFileAccess.Read));
            var zonefile = zip.GetEntry("zone.oez").Open();
            var reader   = new BinaryReader(zonefile);

            var entity = new Entity(position: new Vector3(0, 0, 0), name: "ZoneEntity");

            var nummats   = reader.ReadInt32();
            var materials = new Dictionary <int, Material>();
            var hidden    = new Dictionary <int, bool>();

            for (var i = 0; i < nummats; ++i)
            {
                var flags    = reader.ReadUInt32();
                var numtex   = reader.ReadUInt32();
                var textures = new Texture[numtex];
                for (var j = 0; j < numtex; ++j)
                {
                    var fn    = reader.ReadString();
                    var entry = zip.GetEntry(fn);
                    var zfp   = new BinaryReader(entry.Open());
                    var data  = zfp.ReadBytes((int)entry.Length);
                    var img   = Image.Load(data);
                    textures[j] = Texture.New(game.GraphicsDevice, img);
                }
                hidden[i] = flags == 4;
                var matname = "DiffuseMaterial";
                if (flags == 1)
                {
                    matname = "DiffuseMaskedMaterial";
                }
                else if (flags != 0)
                {
                    matname = "DiffuseTranslucentMaterial";
                }
                var mat = materials[i] = game.Content.Load <Material>(matname).Clone(game.GraphicsDevice);
                mat.Parameters.Set(TexturingKeys.Sampler, game.GraphicsDevice.SamplerStates.AnisotropicWrap);
                mat.Parameters.Set(MaterialKeys.DiffuseMap, textures[0]);
            }

            var objects = new List <Model>();
            var numobjs = reader.ReadUInt32();

            for (var i = 0; i < numobjs; ++i)
            {
                var obj = new Model();
                objects.Add(obj);
                var matoffs = new List <int>();

                var nummeshes = reader.ReadUInt32();
                for (var j = 0; j < nummeshes; ++j)
                {
                    var matid      = reader.ReadInt32();
                    var numvert    = reader.ReadInt32();
                    var verts      = Enumerable.Range(0, numvert).Select(_ => new VertexPositionNormalTexture(reader.ReadVector3(), reader.ReadVector3(), reader.ReadVector2())).ToArray();
                    var numpoly    = reader.ReadInt32();
                    var indices    = Enumerable.Range(0, numpoly * 3).Select(_ => (int)reader.ReadUInt32()).ToArray();
                    var collidable = Enumerable.Range(0, numpoly).Select(_ => reader.ReadUInt32() == 1).ToArray();

                    if (hidden[matid])
                    {
                        continue;
                    }
                    var vertbuffer  = Buffer.Vertex.New(game.GraphicsDevice, verts);
                    var indexbuffer = Buffer.Index.New(game.GraphicsDevice, indices);

                    var md = new MeshDraw {
                        PrimitiveType = PrimitiveType.TriangleList,
                        VertexBuffers = new[] { new VertexBufferBinding(vertbuffer, VertexPositionNormalTexture.Layout, vertbuffer.ElementCount) },
                        IndexBuffer   = new IndexBufferBinding(indexbuffer, true, indexbuffer.ElementCount),
                        DrawCount     = indexbuffer.ElementCount
                    };

                    var mesh = new Mesh()
                    {
                        Draw = md
                    };
                    if (matoffs.Contains(matid))
                    {
                        mesh.MaterialIndex = matoffs.IndexOf(matid);
                    }
                    else
                    {
                        mesh.MaterialIndex = matoffs.Count;
                        matoffs.Add(matid);
                        obj.Materials.Add(materials[matid]);
                    }
                    obj.Add(mesh);
                }
            }

            var component = new ModelComponent(objects[0]);

            entity.Add(component);
            var numplace = reader.ReadUInt32();

            for (var i = 0; i < numplace; ++i)
            {
                component = new ModelComponent(objects[reader.ReadInt32()]);
                var subent = new Entity();
                subent.Transform.Position         = reader.ReadVector3();
                subent.Transform.RotationEulerXYZ = reader.ReadVector3();
                subent.Transform.Scale            = reader.ReadVector3();
                subent.Add(component);
                entity.AddChild(subent);
            }

            return(entity);
        }
        private Entity CreateChildEntity(PhysicsComponent component, ColliderShape shape, RenderGroup renderGroup, bool addOffset)
        {
            if (shape == null)
            {
                return(null);
            }

            switch (shape.Type)
            {
            case ColliderShapeTypes.Compound:
            {
                var entity = new Entity();

                //We got to recurse
                var compound = (CompoundColliderShape)shape;
                for (var i = 0; i < compound.Count; i++)
                {
                    var subShape  = compound[i];
                    var subEntity = CreateChildEntity(component, subShape, renderGroup, true);         //always add offsets to compounds
                    if (subEntity != null)
                    {
                        entity.AddChild(subEntity);
                    }
                }

                entity.Transform.LocalMatrix = Matrix.Identity;
                entity.Transform.UseTRS      = false;

                compound.DebugEntity = entity;

                return(entity);
            }

            case ColliderShapeTypes.Box:
            case ColliderShapeTypes.Capsule:
            case ColliderShapeTypes.ConvexHull:
            case ColliderShapeTypes.Cylinder:
            case ColliderShapeTypes.Sphere:
            case ColliderShapeTypes.Cone:
            case ColliderShapeTypes.StaticPlane:
            case ColliderShapeTypes.StaticMesh:
            case ColliderShapeTypes.Heightfield:
            {
                IDebugPrimitive debugPrimitive;
                var             type = shape.GetType();
                if (type == typeof(HeightfieldColliderShape) || type.BaseType == typeof(HeightfieldColliderShape))
                {
                    if (!updatableDebugMeshCache.TryGetValue(shape, out debugPrimitive))
                    {
                        debugPrimitive = shape.CreateUpdatableDebugPrimitive(graphicsDevice);
                        updatableDebugMeshCache[shape] = debugPrimitive;
                    }
                    if (!updatableDebugMeshes.ContainsKey(shape))
                    {
                        updatableDebugMeshes.Add(shape, debugPrimitive);
                    }
                }
                else if (type == typeof(CapsuleColliderShape) || type == typeof(ConvexHullColliderShape) || type == typeof(StaticMeshColliderShape))
                {
                    if (!debugMeshCache2.TryGetValue(shape, out debugPrimitive))
                    {
                        debugPrimitive = new DebugPrimitive {
                            shape.CreateDebugPrimitive(graphicsDevice)
                        };
                        debugMeshCache2[shape] = debugPrimitive;
                    }
                }
                else
                {
                    if (!debugMeshCache.TryGetValue(shape.GetType(), out debugPrimitive))
                    {
                        debugPrimitive = new DebugPrimitive {
                            shape.CreateDebugPrimitive(graphicsDevice)
                        };
                        debugMeshCache[shape.GetType()] = debugPrimitive;
                    }
                }

                var model = new Model
                {
                    GetMaterial(component, shape),
                };
                foreach (var meshDraw in debugPrimitive.GetMeshDraws())
                {
                    model.Add(new Mesh {
                            Draw = meshDraw
                        });
                }

                var entity = new Entity
                {
                    new ModelComponent
                    {
                        Model       = model,
                        RenderGroup = renderGroup,
                    },
                };

                var offset = addOffset ? Matrix.RotationQuaternion(shape.LocalRotation) * Matrix.Translation(shape.LocalOffset) : Matrix.Identity;

                entity.Transform.LocalMatrix = shape.DebugPrimitiveMatrix * offset * Matrix.Scaling(shape.Scaling);

                entity.Transform.UseTRS = false;

                shape.DebugEntity = entity;

                return(entity);
            }

            default:
                return(null);
            }
        }
Exemplo n.º 35
0
        private static void BuildSmsTestModel()
        {
            EntityField field = null;

            /** User **/
            EntityClass user = new EntityClass();

            user.Name       = "Principal";
            user.Visibility = "public";

            field              = new EntityField();
            field.Name         = "Id";
            field.IsPrimaryKey = true;
            field.Type         = new Int();
            user.Fields.Add(field);

            /** IDescription Definition **/
            EntityInterface iDescription = new EntityInterface();

            iDescription.Name       = "IDescription";
            iDescription.Visibility = "public";
            EntityMethod getDescription = new EntityMethod();

            getDescription.Name = "GetDescription";
            EntityParameter param = new EntityParameter();

            param.IsReturn = true;
            param.Type     = IntrinsicTypes.Create("System.String");
            getDescription.ReturnEntity = param;
            iDescription.Methods.Add(getDescription);

            /** Category Definition **/

            EntityClass category = new EntityClass();

            category.Name       = "Category";
            category.Visibility = "public";
            //category.Interfaces.Add(iDescription);

            field              = new EntityField();
            field.Name         = "Id";
            field.IsPrimaryKey = true;
            field.Type         = new Int();
            category.Fields.Add(field);

            field            = new EntityField();
            field.Name       = "Description";
            field.IsRequired = true;
            field.MaxSize    = 500;
            field.Type       = new Loki.DataRepresentation.IntrinsicEntities.String();
            category.Fields.Add(field);

            /** Sms Definition **/

            EntityClass message = new EntityClass();

            message.Name       = "SmsBase";
            message.IsAbstract = true;
            message.Visibility = "public";
            //message.Interfaces.Add(iDescription);

            field              = new EntityField();
            field.Name         = "Id";
            field.IsPrimaryKey = true;
            field.Type         = new Int();
            message.Fields.Add(field);

            field            = new EntityField();
            field.Name       = "Description";
            field.IsRequired = true;
            field.MaxSize    = 500;
            field.Default    = "No Description";
            field.Type       = new Loki.DataRepresentation.IntrinsicEntities.String();
            message.Fields.Add(field);

            field            = new EntityField();
            field.Name       = "Category";
            field.Type       = category;
            field.Mult       = Multiplicity.ManyToOne;
            field.IsRequired = true;
            message.Fields.Add(field);

            field            = new EntityField();
            field.Name       = "Principal";
            field.Type       = user;
            field.Mult       = Multiplicity.ManyToOne;
            field.IsRequired = true;
            message.Fields.Add(field);

            field          = new EntityField();
            field.Name     = "Messages";
            field.Type     = message;
            field.Mult     = Multiplicity.OneToMany;
            field.InfoOnly = true;
            user.Fields.Add(field);

            field          = new EntityField();
            field.Name     = "Messages";
            field.Type     = message;
            field.InfoOnly = true;
            field.Mult     = Multiplicity.OneToMany;
            category.Fields.Add(field);

            /** ImageSms **/
            EntityClass imageSms = new EntityClass();

            imageSms.Name       = "ImageSms";
            imageSms.Visibility = "public";
            imageSms.Parent     = message;

            field            = new EntityField();
            field.Name       = "ImageUrl";
            field.Type       = new Loki.DataRepresentation.IntrinsicEntities.String();
            field.IsRequired = true;
            field.Default    = "#";
            imageSms.Fields.Add(field);

            /** TextSms **/
            EntityClass textSms = new EntityClass();

            textSms.Name       = "TextSms";
            textSms.Visibility = "public";
            textSms.Parent     = message;

            field            = new EntityField();
            field.Name       = "Text";
            field.Type       = new Loki.DataRepresentation.IntrinsicEntities.String();
            field.IsRequired = true;
            field.Default    = "Empty";
            textSms.Fields.Add(field);

            /** Setting up project **/
            Model list = new Model();

            list.Add(category);
            list.Add(iDescription);
            list.Add(user);
            list.Add(message);
            list.Add(imageSms);
            list.Add(textSms);
            smsTestModel.Model = list;
        }
Exemplo n.º 36
0
        public virtual void DataChanged(IDataChange dataChange, DateTime dispatchTime, long sequenceId)
        {
            dataChange = dataChange.Derive(InterestedEntityTypes);
            if (dataChange.IsEmpty)
            {
                return;
            }
            ISet <Object> directObjectsToDelete = null;

            ISet <Type> requestedTypes = new HashSet <Type>();
            IDictionary <Type, IEntityMetaData> typeToMetaDataDict = new Dictionary <Type, IEntityMetaData>();

            GuiThreadHelper.InvokeInGuiAndWait(delegate()
            {
                IList <T> entities = Model.Objects;

                for (int i = entities.Count; i-- > 0;)
                {
                    Object entity = entities[i];

                    requestedTypes.Add(entity.GetType());
                }
            });

            IList <IDataChangeEntry> dataChangeEntries = dataChange.Inserts;

            for (int a = dataChangeEntries.Count; a-- > 0;)
            {
                requestedTypes.Add(dataChangeEntries[a].EntityType);
            }
            dataChangeEntries = dataChange.Updates;
            for (int a = dataChangeEntries.Count; a-- > 0;)
            {
                requestedTypes.Add(dataChangeEntries[a].EntityType);
            }
            dataChangeEntries = dataChange.Deletes;
            for (int a = dataChangeEntries.Count; a-- > 0;)
            {
                requestedTypes.Add(dataChangeEntries[a].EntityType);
            }

            IList <IEntityMetaData> metaDatas = EntityMetaDataProvider.GetMetaData(ListUtil.ToList(requestedTypes));

            foreach (IEntityMetaData metaData in metaDatas)
            {
                typeToMetaDataDict[metaData.EntityType] = metaData;
            }

            bool consistsOnlyOfDirectDeletes = false;

            if (dataChange.Deletes.Count > 0)
            {
                consistsOnlyOfDirectDeletes = true;
                foreach (IDataChangeEntry deleteEntry in dataChange.Deletes)
                {
                    if (deleteEntry is DirectDataChangeEntry)
                    {
                        if (directObjectsToDelete == null)
                        {
                            directObjectsToDelete = new IdentityHashSet <Object>();
                        }
                        directObjectsToDelete.Add(((DirectDataChangeEntry)deleteEntry).Entry);
                    }
                    else
                    {
                        consistsOnlyOfDirectDeletes = false;
                    }
                }
            }

            IList <T> interestingEntities = null;

            Object[]                contextInformation = GetContextInformation();
            IFilterDescriptor       filterDescriptor   = GetFilterDescriptor();
            IList <ISortDescriptor> sortDescriptors    = GetSortDescriptors();
            IPagingRequest          pagingRequest      = GetPagingRequest();

            IPagingResponse         pagingResponse  = null;
            List <IDataChangeEntry> modifiedEntries = new List <IDataChangeEntry>();

            modifiedEntries.AddRange(dataChange.All);

            if (!consistsOnlyOfDirectDeletes)
            {
                interestingEntities = CacheContext.ExecuteWithCache(CacheProvider.GetCurrentCache(), delegate()
                {
                    ConfigureCacheWithEagerLoads(Cache);
                    if (Refresher is IPagingRefresher <T> )
                    {
                        interestingEntities = new List <T>();
                        pagingResponse      = ((IPagingRefresher <T>)Refresher).Refresh(modifiedEntries, filterDescriptor, sortDescriptors, pagingRequest, contextInformation);
                        foreach (Object obj in pagingResponse.Result)
                        {
                            interestingEntities.Add((T)obj);
                        }
                        return(interestingEntities);
                    }
                    else
                    {
                        if (filterDescriptor != null || sortDescriptors != null)
                        {
                            contextInformation    = new Object[2];
                            contextInformation[0] = filterDescriptor;
                            contextInformation[1] = sortDescriptors;
                        }

                        return(((IRefresher <T>)Refresher).Refresh(modifiedEntries, contextInformation));
                    }
                });
            }
            GuiThreadHelper.InvokeInGuiAndWait(delegate()
            {
                IList <T> entities = Model.Objects;

                ISet <T> entitiesToAdd                           = null;
                ISet <T> entitiesToRemove                        = null;
                IDictionary <T, T> entitiesToReplace             = null;
                IDictionary <IObjRef, T> oldObjRefToOldEntityMap = null;
                bool mergeModel = false;

                if (interestingEntities != null && interestingEntities.Count > 0)
                {
                    entitiesToAdd           = new IdentityHashSet <T>(interestingEntities);
                    entitiesToRemove        = new IdentityHashSet <T>(entities);
                    entitiesToReplace       = new IdentityDictionary <T, T>();
                    oldObjRefToOldEntityMap = new Dictionary <IObjRef, T>();
                    mergeModel = true;
                }
                for (int i = entities.Count; i-- > 0;)
                {
                    T oldEntity = entities[i];
                    if (directObjectsToDelete != null && directObjectsToDelete.Contains(oldEntity))
                    {
                        if (entitiesToRemove != null)
                        {
                            entitiesToRemove.Remove(oldEntity);
                        }
                        Model.RemoveAt(i);
                        continue;
                    }
                    Type oldEntityType       = ProxyHelper.GetRealType(oldEntity.GetType());
                    PrimitiveMember idMember = typeToMetaDataDict[oldEntityType].IdMember;
                    Object oldEntityId       = idMember.GetValue(oldEntity, false);
                    if (oldEntityId == null)
                    {
                        if (entitiesToRemove != null)
                        {
                            entitiesToRemove.Remove(oldEntity);
                        }
                        // Unpersisted object. This object should not be removed
                        // only because of a background DCE
                        continue;
                    }
                    bool entryRemoved = false;
                    foreach (IDataChangeEntry deleteEntry in dataChange.Deletes)
                    {
                        if (deleteEntry is DirectDataChangeEntry)
                        {
                            continue;
                        }
                        Object id = deleteEntry.Id;
                        if (!EqualsItems(oldEntityType, oldEntityId, deleteEntry.EntityType, id))
                        {
                            continue;
                        }
                        if (entitiesToRemove != null)
                        {
                            entitiesToRemove.Remove(oldEntity);
                        }
                        Model.RemoveAt(i);
                        entryRemoved = true;
                        break;
                    }
                    if (entryRemoved)
                    {
                        continue;
                    }
                    if (mergeModel)
                    {
                        IObjRef oldObjRef   = new ObjRef(oldEntityType, ObjRef.PRIMARY_KEY_INDEX, oldEntityId, null);
                        T existingOldEntity = DictionaryExtension.ValueOrDefault(oldObjRefToOldEntityMap, oldObjRef);
                        if (existingOldEntity == null)
                        {
                            oldObjRefToOldEntityMap.Add(oldObjRef, oldEntity);
                        }
                        else if (!Object.ReferenceEquals(existingOldEntity, oldEntity))
                        {
                            // Force duplicate key exception
                            oldObjRefToOldEntityMap.Add(oldObjRef, oldEntity);
                        }
                    }
                }
                if (oldObjRefToOldEntityMap != null && oldObjRefToOldEntityMap.Count > 0)
                {
                    IDictionary <IObjRef, T> newObjRefToNewEntityMap = new Dictionary <IObjRef, T>();
                    for (int a = interestingEntities.Count; a-- > 0;)
                    {
                        T newEntity              = interestingEntities[a];
                        Type newEntityType       = ProxyHelper.GetRealType(newEntity.GetType());
                        PrimitiveMember idMember = typeToMetaDataDict[newEntityType].IdMember;
                        Object newEntityId       = idMember.GetValue(newEntity, false);

                        IObjRef newObjRef = new ObjRef(newEntityType, ObjRef.PRIMARY_KEY_INDEX, newEntityId, null);
                        newObjRefToNewEntityMap.Add(newObjRef, newEntity);
                    }
                    DictionaryExtension.Loop(oldObjRefToOldEntityMap, delegate(IObjRef objRef, T oldEntity)
                    {
                        T newEntity = DictionaryExtension.ValueOrDefault(newObjRefToNewEntityMap, objRef);
                        if (newEntity == null)
                        {
                            // Nothing to do if current oldEntity has no corresponding newEntity
                            return;
                        }
                        entitiesToAdd.Remove(newEntity);
                        if (!Object.ReferenceEquals(oldEntity, newEntity) &&
                            (dataChange.IsLocalSource || !(oldEntity is IDataObject) || !((IDataObject)oldEntity).ToBeUpdated))
                        {
                            entitiesToReplace[oldEntity] = newEntity;
                        }
                        entitiesToRemove.Remove(oldEntity);
                    });
                }

                if (mergeModel)
                {
                    for (int a = entities.Count; a-- > 0;)
                    {
                        T item = entities[a];
                        if (entitiesToRemove.Contains(item))
                        {
                            Model.RemoveAt(a);
                            continue;
                        }
                        T replacingItem = DictionaryExtension.ValueOrDefault(entitiesToReplace, item);
                        if (replacingItem != null)
                        {
                            Model.Replace(a, replacingItem);
                            continue;
                        }
                    }
                    IEnumerator <T> enumerator = entitiesToAdd.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        T entityToAdd = enumerator.Current;
                        Model.Add(entityToAdd);
                    }

                    if (hasPagedViewModel)
                    {
                        UpdatePagingInformation(pagingResponse);
                    }
                    UpdateAfterDCE();
                }
            });
        }
Exemplo n.º 37
0
        public override void Run(string path)
        {
            Model model = new Model();

            // Create a definition of a square shape.

            CompDef square = new CompDef(
                "Flat",
                "A Square");

            // Add a square polygon to the definition.

            Point3[] squarePoints =
            {
                new Point3(-1, 0, -1),
                new Point3(1,  0, -1),
                new Point3(1,  0,  1),
                new Point3(-1, 0, 1)
            };

            square.Add(squarePoints);

            // Add the square definition to the model.

            model.Add(square);

            // Create an instance of a definition that does not
            // yet exist in the model.

            CompInst pointyInstance = new CompInst
            {
                // Refer here to a definition we'll create later.

                ComponentName = "Pointy",
                InstanceName  = "Tri the Angle"
            };

            // Move the instance away from the origin a bit.

            pointyInstance.Transform.Translation.Y = 1;
            pointyInstance.Transform.Rotation.Z    = -20;

            // Add the instance to the square's definition.

            square.Add(pointyInstance);

            // Instantiate the square definition.

            CompInst squareInstance = new CompInst
            {
                ComponentName = "Flat",
                InstanceName  = "Quad the First"
            };

            // Add the instance to the model.

            model.Add(squareInstance);

            // Now create the "Pointy" definition (a triangle).

            CompDef pointy = new CompDef(
                "Pointy",
                "A Triangle");

            // Define a triangular shape.

            Point3[] pointyPoints =
            {
                new Point3(-1, 0, -1),
                new Point3(1,  0, -1),
                new Point3(0,  0, 1)
            };

            // Add the shape to the defintion.

            pointy.Add(pointyPoints);

            // Add the definition to the model.

            model.Add(pointy);

            model.WriteSketchUpFile(path + @"\ForwardComponent.skp");
        }
        public void Generate(IServiceRegistry services, Model model)
        {
            if (services == null) throw new ArgumentNullException("services");
            if (model == null) throw new ArgumentNullException("model");

            var graphicsDevice = services.GetSafeServiceAs<IGraphicsDeviceService>().GraphicsDevice;

            var data = this.CreatePrimitiveMeshData();

            if (data.Vertices.Length == 0)
            {
                throw new InvalidOperationException("Invalid GeometricPrimitive [{0}]. Expecting non-zero Vertices array");
            }

            var boundingBox = BoundingBox.Empty;
            for (int i = 0; i < data.Vertices.Length; i++)
                BoundingBox.Merge(ref boundingBox, ref data.Vertices[i].Position, out boundingBox);

            BoundingSphere boundingSphere;
            unsafe
            {
                fixed (void* verticesPtr = data.Vertices)
                    BoundingSphere.FromPoints((IntPtr)verticesPtr, 0, data.Vertices.Length, VertexPositionNormalTexture.Size, out boundingSphere);
            }

            var originalLayout = data.Vertices[0].GetLayout();

            // Generate Tangent/BiNormal vectors
            var resultWithTangentBiNormal = VertexHelper.GenerateTangentBinormal(originalLayout, data.Vertices, data.Indices);

            // Generate Multitexcoords
            var result = VertexHelper.GenerateMultiTextureCoordinates(resultWithTangentBiNormal);

            var meshDraw = new MeshDraw();

            var layout = result.Layout;
            var vertexBuffer = result.VertexBuffer;
            var indices = data.Indices;

            if (indices.Length < 0xFFFF)
            {
                var indicesShort = new ushort[indices.Length];
                for (int i = 0; i < indicesShort.Length; i++)
                {
                    indicesShort[i] = (ushort)indices[i];
                }
                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indicesShort).RecreateWith(indicesShort), false, indices.Length);
            }
            else
            {
                if (graphicsDevice.Features.Profile <= GraphicsProfile.Level_9_3)
                {
                    throw new InvalidOperationException("Cannot generate more than 65535 indices on feature level HW <= 9.3");
                }

                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices).RecreateWith(indices), true, indices.Length);
            }

            meshDraw.VertexBuffers = new[] { new VertexBufferBinding(Buffer.New(graphicsDevice, vertexBuffer, BufferFlags.VertexBuffer).RecreateWith(vertexBuffer), layout, data.Vertices.Length) };

            meshDraw.DrawCount = indices.Length;
            meshDraw.PrimitiveType = PrimitiveType.TriangleList;

            var mesh = new Mesh { Draw = meshDraw, BoundingBox = boundingBox, BoundingSphere = boundingSphere };

            model.BoundingBox = boundingBox;
            model.BoundingSphere = boundingSphere;
            model.Add(mesh);

            if (MaterialInstance != null && MaterialInstance.Material != null)
            {
                model.Materials.Add(MaterialInstance);
            }
        }
Exemplo n.º 39
0
        private static void BuildInterfaceTestModel()
        {
            EntityInterface iPerson = GetInterface();

            Model list = new Model();
            list.Add(iPerson);
            interfaces.Model = list;
        }