Inheritance: MonoBehaviour
Beispiel #1
0
 public static EffectDefinition getCubeEffectDefinition(Cube.CubeEffect_e effect)
 {
     if (EFFECT_DEFS.ContainsKey(effect)) {
         return EFFECT_DEFS[effect];
     }
     return new EffectDefinition();
 }
        static void Main(string[] args)
        {
            // Create four-element Shape array
            Shape[] shapes = new Shape[4];

            // Populate array with objects that implement Shape
            shapes[0] = new Square(10); //length of side is 10
            shapes[1] = new Circle(5); //radius is 5
            shapes[2] = new Sphere(5); //radius is 5
            shapes[3] = new Cube(10); //length of side is 10

            // Process each element in array shapes
            foreach (Shape shape in shapes)
            {
                if (shape is TwoDimensionalShape)
                {
                    Console.WriteLine(shape);
                    Console.WriteLine("The area is {0:N} square units.", shape.Area);
                    Console.WriteLine();
                }
                else
                {
                    // Downcast Shape reference to ThreeDimensionalShape
                    ThreeDimensionalShape Shape = (ThreeDimensionalShape)shape;
                    Console.WriteLine(shape);
                    Console.WriteLine("The area is {0:N} square units.", shape.Area);
                    Console.WriteLine("The volume is {0:N} cubic units.", Shape.Volume);
                    Console.WriteLine();
                }
            }
            Console.Read();
        }
Beispiel #3
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="cube">
 /// A <see cref="Cube"/>
 /// </param>
 public MazeCube(Cube cube)
 {
     this.cube = cube;
     cube.userData = this;
     this.cube.TiltEvent += OnTilt;
     this.cube.ButtonEvent += OnButton;
 }
Beispiel #4
0
        static void Main(string[] args)
        {
            string command = Console.ReadLine();
            while(command != "End")
            {
                string[] tokens = command.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
                switch(tokens[0])
                {
                    case "Cube":
                        Cube cube = new Cube(double.Parse(tokens[1]));
                        Console.WriteLine("{0:F3}", VolumeCalculator.CubeVolume(cube));
                        break;
                    case "Cylinder":
                        Cylinder cylinder = new Cylinder(double.Parse(tokens[1]), double.Parse(tokens[2]));
                        Console.WriteLine("{0:F3}", VolumeCalculator.CylinderVolume(cylinder));
                        break;
                    case "TrianglePrism":
                        TriangularPrism prism = new TriangularPrism(double.Parse(tokens[1]), double.Parse(tokens[2]),
                            double.Parse(tokens[3]));
                        Console.WriteLine("{0:F3}", VolumeCalculator.TriangularPrismVolume(prism));
                        break;
                }

                command = Console.ReadLine();
            }
        }
Beispiel #5
0
 public void addEffect(Cube.CubeEffect_e effect)
 {
     if (effects.Contains(effect)) {
         return;
     }
     effects.Add(effect);
 }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormSceneSample"/> class.
        /// </summary>
        public FormSceneSample()
        {
            InitializeComponent();

            sceneControl1.MouseDown += new MouseEventHandler(FormSceneSample_MouseDown);
            sceneControl1.MouseMove += new MouseEventHandler(FormSceneSample_MouseMove);
            sceneControl1.MouseUp += new MouseEventHandler(sceneControl1_MouseUp);

            //  Add some design-time primitives.
            sceneControl1.Scene.SceneContainer.AddChild(new
                UnU.OpenGL.SceneGraph.Primitives.Grid());
            sceneControl1.Scene.SceneContainer.AddChild(new
                UnU.OpenGL.SceneGraph.Primitives.Axies());

            //  Create a light.
            Light light = new Light()
            {
                On = true,
                Position = new Vertex(3, 10, 3),
                GLCode = OpenGL.GL_LIGHT0
            };

            //  Add the light.
            sceneControl1.Scene.SceneContainer.AddChild(light);

            //  Create a sphere.
            Cube cube = new Cube();
            cube.AddEffect(arcBallEffect);

            //  Add it.
            sceneControl1.Scene.SceneContainer.AddChild(cube);

            //  Add the root element to the tree.
            AddElementToTree(sceneControl1.Scene.SceneContainer, treeView1.Nodes);
        }
        /// <summary>
        /// Solves the cube and returns the list of the movements to be done.
        /// </summary>
        /// <returns>List of movements to be sent to the robot</returns>
        public List<Movement> Solve(String inputCubeString)
        {
            // isto não existirá! é apenas para testarmos enviando como entrada do Solver um cubo em formato string
            // para testarmos o algoritmo dos movimentos... na implementação final, esta linha
            // No algoritmo real, passo da visão já fornecerá a estrutura do cubo montada
            Cube = TranslateInputStringToCube(inputCubeString);

            // valida o cubo, primeiramente
            if (!Cube.Validate())
                return new List<Movement>();

            // traduz cubo para a entrada da DLL
            inputCubeString = TranslateCubeToSolverInput(Cube);

            // chama dll em C
            String outputOfSolver = SolveRubikCube(inputCubeString);

            // traduz movimentos retornados para uma lista de Movement (movements)
            // os RotateFaceMovement.PositionFace não estão preenchidos, pois nesta etapa,
            // ainda não se tem esta informação. eles serão preenchdiso no AdjustMovementsBasedOnTheClaws
            List<Movement> movements = TranslateStringToListOfMovements(outputOfSolver);

            // add rotation movements to bring faces to the robot claws
            AdjustMovementsBasedOnTheClaws(movements);

            return movements;
        }
Beispiel #8
0
        /// <summary>
        /// Converts this object to an OpenSCAD script
        /// </summary>
        /// <returns>Script for this object</returns>
        public override string ToString()
        {
            OSCADObject inner = new Cube(new Vector3(this.Size.X - WallThickness*2, 
                this.Size.Y - WallThickness*2, 
                this.Size.Z - WallThickness*2),
                this.Center);
                        
            if (!this.Bottom && !this.Top)
            {
                ((Cube)inner).Size.Z += WallThickness * 4;
            }
            else if (!this.Top)
            {
                ((Cube)inner).Size.Z += WallThickness*2;
                inner = inner.Translate(0, 0, WallThickness);
            }
            else if (!this.Bottom)
            {
                ((Cube)inner).Size.Z += WallThickness*2;
                inner = inner.Translate(0, 0, -WallThickness);
            }


            if (!this.Center)
            {
                inner = inner.Translate(this.WallThickness, this.WallThickness, this.WallThickness);
            }

            OSCADObject box = new Cube(this.Size, this.Center) - inner;

            return box.ToString();
        }
Beispiel #9
0
	public CubeMesh Calculate(ref int visualVertexCount, ref int collisionVertexCount, Cube[,,] cubes, CubeLegend cubeLegend, ColliderType colliderType, string cubeTag) {
		// TODO: Put this back in when preprocessor directives are supported in Boo
		// Use UNITY_EDITOR
		//CubeGeneratorProgressEditor.ReportCube(chunk.gridPosition, gridPosition) if chunk
		
		// TODO: Vector3i.zero
		// TODO: Cached cube position of the chunk
		var position = (indexes - (chunk.dimensionsInCubes * chunk.gridPosition)).ToVector3() * cubeSize;
		
		var meshData = new CubeMesh();
		
		if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Down))  AddSide(Direction.Down,  position, ref visualVertexCount, cubeLegend, meshData);
		if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Up))	  AddSide(Direction.Up,    position, ref visualVertexCount, cubeLegend, meshData);
		if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Right)) AddSide(Direction.Right, position, ref visualVertexCount, cubeLegend, meshData);
		if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Left))  AddSide(Direction.Left,  position, ref visualVertexCount, cubeLegend, meshData);
		if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Front)) AddSide(Direction.Front, position, ref visualVertexCount, cubeLegend, meshData);
		if(!AdjacentCubeExistsInsideChunk(cubes, indexes.Back))  AddSide(Direction.Back,  position, ref visualVertexCount, cubeLegend, meshData);
		
		if (cubeLegend.cubeDefinitions[type].hasCollision) {
			if(colliderType == ColliderType.MeshColliderPerChunk) {
				if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Down))  AddCollisionSide(Direction.Down,  position, ref collisionVertexCount, cubeLegend, meshData);
				if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Up))	   AddCollisionSide(Direction.Up,    position, ref collisionVertexCount, cubeLegend, meshData);
				if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Right)) AddCollisionSide(Direction.Right, position, ref collisionVertexCount, cubeLegend, meshData);
				if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Left))  AddCollisionSide(Direction.Left,  position, ref collisionVertexCount, cubeLegend, meshData);
				if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Front)) AddCollisionSide(Direction.Front, position, ref collisionVertexCount, cubeLegend, meshData);
				if(!AdjacentCubeExistsInsideChunkWithCollision(cubes, cubeLegend, indexes.Back))  AddCollisionSide(Direction.Back,  position, ref collisionVertexCount, cubeLegend, meshData);
			}
			else if(colliderType == ColliderType.BoxColliderPerCube) {
				// TODO: Defer this until the game objects are being created for async compatibility
//				if(generateCollider) CreateCollision(cubeTag);
			}
		}
		return meshData;
	}
	public void Configure()
	{
		Cube = FindObjectOfType<Cube>();

		if ( Node == null ) return;

		if ( Node.Type == NodeTypeEnum.Start )
		{
			var go = Instantiate( Cube.StartPointPrefab ) as GameObject;
			if ( go != null )
			{
				go.transform.parent = transform;
				go.transform.localPosition = Vector3.zero;
				go.transform.localEulerAngles = new Vector3( -90, 0, 0 );
			}

		}
		else if ( Node.Type == NodeTypeEnum.End )
		{
			var go = Instantiate( Cube.EndPointPrefab ) as GameObject;
			if ( go != null )
			{
				go.transform.parent = transform;
				go.transform.localPosition = Vector3.zero;
				go.transform.localEulerAngles = new Vector3( -90, 0, 0 );
			}
		}

		Node.Quad = this;

		StartCoroutine( WaitForFrame() );
	}
Beispiel #11
0
        /// <summary>
        /// Draws to the supplied cube.
        /// </summary>
        /// <param name='cube'>
        /// The cube to which the room should be drawn.
        /// </param>
        public void DrawTo(Cube cube)
        {
            // draw the background
            cube.FillScreen(bgColor);

            // draw the center
            cube.FillRect(passageColor, segmentSize, segmentSize, segmentSize, segmentSize);

            // draw open passages
            for (int i=0; i<entryStates.Length; i++)
            {
                if (entryStates[i] == EntryState.Closed) continue;
                int x=segmentSize, y=segmentSize;
                switch ((Cube.Side)i)
                {
                case Cube.Side.BOTTOM:
                    y = 2*segmentSize;
                    break;
                case Cube.Side.LEFT:
                    x = 0;
                    break;
                case Cube.Side.RIGHT:
                    x = 2*segmentSize;
                    break;
                case Cube.Side.TOP:
                    y = 0;
                    break;
                }
                cube.FillRect(passageColor, x, y, segmentSize, segmentSize);
            }

            // paint the cube
            cube.Paint();
        }
    //TODO: fixup display of numbers to match .net
    static void Main()
    {
        // Input the side:
        System.Console.Write("Enter the side: ");
        double side = 5;//double.Parse(System.Console.ReadLine());

        // Compute the areas:
        Square s = new Square(side);
        Cube c = new Cube(side);

        // Display the results:
        System.Console.Write("Area of the square =");
        System.Console.WriteLine(s.Area);
        System.Console.Write("Area of the cube =");
        System.Console.WriteLine(c.Area);
        // System.Console.WriteLine();

        // Input the area:
        System.Console.Write("Enter the area: ");
        double area = 125; //double.Parse(System.Console.ReadLine());

        // Compute the sides:
        s.Area = area;
        c.Area = area * 6;

        // Display the results:
        System.Console.Write("Side of the square = ");
        System.Console.WriteLine((int)s.side);
        System.Console.Write("Side of the cube = ");
        System.Console.WriteLine((int)c.side);
    }
Beispiel #13
0
        public Robot(World w, Vector2 pos)
        {
            cube = new Cube(new Vector3(pos.X, 0, pos.Y), RM.GetTexture("robot"));
            Position = pos;
            Direction = new Vector2(0, 0);
            CanRun = false;
            supportsCamera = true;

            HudIcons.Add(new HudIcon() { text = "Robocam", texture = RM.GetTexture("camera"), Action = (() => w.ToggleCamera(this)) });
            HudIcons.Add(new HudIcon() { text = "Move", texture = RM.GetTexture("arrowupicon"), Action = (() => moving = !moving) });
            HudIcons.Add(new HudIcon() { text = "Turn left", texture = RM.GetTexture("arrowlefticon"), Action = (() => {
                Matrix cameraRotation = Matrix.CreateRotationY(0.05f);
                Vector3 rotTarget = LookDir.ToVector3();
                var result = Vector3.Transform(rotTarget, cameraRotation);
                LookDir = result.ToVector2();
                lastCamDir = result;
            }), OnDown = true });
            HudIcons.Add(new HudIcon()
            {
                text = "Turn right",
                texture = RM.GetTexture("arrowrighticon"),
                Action = (() =>
                {
                    Matrix cameraRotation = Matrix.CreateRotationY(-0.05f);
                    Vector3 rotTarget = LookDir.ToVector3();
                    var result = Vector3.Transform(rotTarget, cameraRotation);
                    LookDir = result.ToVector2();
                    lastCamDir = result;
                }),
                OnDown = true
            });
            HudIcons.Add(new HudIcon() { text = "Grab/drop", texture = RM.GetTexture("grabicon"), Action = ToggleGrab });
        }
Beispiel #14
0
 public Cube.Side SideOf(Cube c)
 {
     if (this._neighbors[(int)Cube.Side.TOP] == c) return Cube.Side.TOP;
     if (this._neighbors[(int)Cube.Side.RIGHT] == c) return Cube.Side.RIGHT;
     if (this._neighbors[(int)Cube.Side.LEFT] == c) return Cube.Side.LEFT;
     if (this._neighbors[(int)Cube.Side.BOTTOM] == c) return Cube.Side.BOTTOM;
     return Cube.Side.NONE;
 }
Beispiel #15
0
        public Incinerator(Vector2 position)
        {
            this.Position = position;
            cube = new Cube(new Vector3(position.X, 0, position.Y), RM.GetTexture("incinerator"));

            cube.ScaleVector = new Vector3(24, 64, 24);
            cube.SetPosition(position.ToVector3() + new Vector3(0, -56, 0));
        }
Beispiel #16
0
 public AlarmPanel(Vector2 pos)
     : base(pos)
 {
     workTime = 0;
     cube = new Cube(new Vector3(pos.X, 0, pos.Y), RM.GetTexture("work"));
     cube.ScaleVector = new Vector3(8, 1, 8);
     cube.SetPosition(Position.ToVector3());
 }
Beispiel #17
0
 public static void Main()
 {
    double x = 5.2;
    Square s = new Square(x);
    Square c = new Cube(x);
    Console.WriteLine("Area of Square = {0:F2}", s.Area());
    Console.WriteLine("Area of Cube = {0:F2}", c.Area());
 }
        public void DefaultSettingsInit_Test()
        {
            Cube<int> cube = new Cube<int>();

            cube.Initialize();

            Assert.AreEqual(StorageType.Molap,cube.Storage.StorageType);
        }
Beispiel #19
0
 public void refreshPanels(Cube c)
 {
     for (int i= 0; i < 6; i++)
     {
         Renderer rend = panels[i].GetComponent<Renderer>();
         rend.enabled = true;
         rend.material.color = c.getColors()[i];
     }
 }
Beispiel #20
0
        public Actor( CubeGame game, CubeScreen screen, Cube cube, Vector3 worldPos, Direction upDir )
            : this(game, screen)
        {
            Cube = cube;
            mCubePosition = worldPos;
            UpDir = upDir;

            CubeFace = Cube.GetFaceFromPosition( mCubePosition );
        }
Beispiel #21
0
	CubeMesh CalculateRenderableCube(Cube cube, ref int visualVertexCount, ref int collisionVertexCount, Cube[,,] cubes, Vector3i gridPosition) {
    	if (cube == null) return null;
	    cube.cubeSize = cubeSize;
		
	    cube.indexes = gridPosition;
	    cube.chunk = this;
	    var cubeMesh = cube.Calculate(ref visualVertexCount, ref collisionVertexCount,cubes, cubeLegend, cubeObject.colliderType, cubeObject.cubeTag);
	    return cubeMesh;
	}
Beispiel #22
0
 public bool Contains(Cube c)
 {
     for (int i = 0; i < 4; i++)
     {
         if (this._neighbors[i] == c)
             return true;
     }
     return false;
 }
Beispiel #23
0
 public static void Main()
 {
     double x = 5.2;
     Square s = new Square(x);
     Square c = new Cube(x);
     Console.WriteLine("Area of Square = {0}", string.Format("{0:0.00}", s.Area()));
     Console.WriteLine("Area of Cube = {0}", string.Format("{0:0.00}", c.Area()));
     Console.ReadLine();
 }
        public static List<DimensionUsage> GetDimensionUsage(Cube c)
        {
            List<CubeDimension> listCubeDimensions = new List<CubeDimension>();
            foreach (CubeDimension cd in c.Dimensions)
            {
                listCubeDimensions.Add(cd);
            }

            List<DimensionUsage> dimUsage = new List<DimensionUsage>();
            foreach (MeasureGroup mg in c.MeasureGroups)
            {
                System.Diagnostics.Trace.Write("mg " + mg.Name);
                foreach (MeasureGroupDimension mgdim in mg.Dimensions)
                {
                    System.Diagnostics.Trace.Write(",mgdim " + mgdim.Dimension.Name);
                    if (mgdim is ReferenceMeasureGroupDimension)
                    {
                        ReferenceMeasureGroupDimension refMgDim = (ReferenceMeasureGroupDimension)mgdim;
                        getReferencedMeasureGroupAttributeUsage(dimUsage, mg, refMgDim);
                    }
                    else if (mgdim is DegenerateMeasureGroupDimension)
                    {
                        DegenerateMeasureGroupDimension degMgDim = (DegenerateMeasureGroupDimension)mgdim;
                        getFactMeasureGroupAttributeUsage(dimUsage, mg, degMgDim);
                    }
                    else if (mgdim is ManyToManyMeasureGroupDimension)
                    {
                        ManyToManyMeasureGroupDimension m2mMgDim = (ManyToManyMeasureGroupDimension)mgdim;
                        getManyToManyMeasureGroupAttributeUsage(dimUsage, mg, m2mMgDim);
                    }
                    else if (mgdim is DataMiningMeasureGroupDimension)
                    {
                        DataMiningMeasureGroupDimension dmMgDim = (DataMiningMeasureGroupDimension)mgdim;
                        getDataMiningMeasureGroupAttributeUsage(dimUsage, mg, dmMgDim);
                    }
                    else if (mgdim is RegularMeasureGroupDimension)
                    {
                        RegularMeasureGroupDimension regMDdim = (RegularMeasureGroupDimension)mgdim;
                        getRegularMeasureGroupAttributeUsage(dimUsage, mg, regMDdim);
                    }
                    if (listCubeDimensions.Contains(mgdim.CubeDimension))
                    {
                        listCubeDimensions.Remove(mgdim.CubeDimension);
                    }
                }
            
            }

            //add any cube dimensions which aren't related to any measure groups
            foreach (CubeDimension cd in listCubeDimensions)
            {
                DimensionUsage du = new DimensionUsage(string.Empty, null, cd, cd.Dimension);
                dimUsage.Add(du);
            }

            return dimUsage;
        }
Beispiel #25
0
 public Human(World world, Vector2 pos)
 {
     cube = new Cube(new Vector3(pos.X, 0, pos.Y), RM.GetTexture("head"));
     Position = pos;
     Direction = new Vector2(0, 0);
     PanicLevel = 0;
     CurrentTask = new GoToNearestPathNodeTask(world, this);
     this.World = world;
     CanRun = true;
 }
Beispiel #26
0
        public Crate(Vector2 position)
        {
            this.Position = position;
            cube = new Cube(new Vector3(position.X, 0, position.Y), RM.GetTexture("crate"));

            cube.ScaleVector = new Vector3(8, 8, 8);
            cube.SetPosition(Position.ToVector3());
            CanRun = true;
            WantsToRun = true;
        }
Beispiel #27
0
        public Block(Model model, Vector3 position, Type type)
            : base(model, position)
        {
            CurrentState = State.UnTouched;
            Demolished = false;
            BlockType = type;
            switch (BlockType)
            {
                case Type.Glass:
                    Mass = 5.0f; // default
                    Life = 1;
                    break;
                case Type.Wood:
                    Mass = 10.0f; // heavier than glass
                    Life = 2;
                    break;
                case Type.Stone:
                    Mass = 20.0f; // heavier than wood
                    Life = 3;
                    break;
                default:
                    break;
            }

            // create the cube
            box = new Cube(position, new Vector3(1.0f, 1.0f, 1.0f));
            triangles = new Triangle[12];
            // top of the cube
            triangles[0] = new Triangle(box.vertices[0], box.vertices[1], box.vertices[2]);
            triangles[1] = new Triangle(box.vertices[0], box.vertices[2], box.vertices[3]);
            // bottom of the cube
            triangles[2] = new Triangle(box.vertices[4], box.vertices[6], box.vertices[5]);
            triangles[3] = new Triangle(box.vertices[4], box.vertices[7], box.vertices[6]);
            // left of the cube
            triangles[4] = new Triangle(box.vertices[4], box.vertices[7], box.vertices[3]);
            triangles[5] = new Triangle(box.vertices[4], box.vertices[3], box.vertices[0]);
            // right of the cube
            triangles[6] = new Triangle(box.vertices[5], box.vertices[6], box.vertices[2]);
            triangles[7] = new Triangle(box.vertices[5], box.vertices[2], box.vertices[1]);
            // front of the cube
            triangles[8] = new Triangle(box.vertices[2], box.vertices[6], box.vertices[7]);
            triangles[9] = new Triangle(box.vertices[2], box.vertices[7], box.vertices[3]);
            // back of the cube
            triangles[10] = new Triangle(box.vertices[5], box.vertices[1], box.vertices[0]);
            triangles[11] = new Triangle(box.vertices[5], box.vertices[0], box.vertices[4]);

            // define normals
            normals = new Vector3[6];
            normals[0] = Vector3.Down; // top of cube
            normals[1] = Vector3.Up; // bottom of cube
            normals[2] = Vector3.Right; // left of cube
            normals[3] = Vector3.Left; // right of cube
            normals[4] = Vector3.Forward; // front of cube
            normals[5] = Vector3.Backward; // back of cube
        }
Beispiel #28
0
        public Bullet(Vector2 pos, Vector2 dir)
            : base(pos)
        {
            cube = new Cube(new Vector3(pos.X, 0, pos.Y), RM.GetTexture("white"));

            cube.ScaleVector = new Vector3(2, 2, 2);
            cube.SetPosition(Position.ToVector3());

            this.Direction = dir;
            this.score = 50;
        }
Beispiel #29
0
 public Bounce(Cube receiver, Vector3Int endPosition, Vector3Int direction)
     : base(receiver, endPosition)
 {
     positions = new List<Vector3Int>();
     position = new Vector3Int (Cube.transform.position);
     Cube = receiver;
     if (endPosition.y > 1 && Level.Singleton.getEntity (endPosition.ToVector3 + Vector3.down) is RubberCube) {
         FindEndPosition (endPosition, direction, 2);
     } else {
         FindEndPosition (endPosition, direction, 1);
     }
 }
Beispiel #30
0
Datei: Door.cs Projekt: Frib/LD25
        public Door(Vector2 position)
        {
            Position = position;
            cube = new Cube(Position.ToVector3(), RM.GetTexture("door"));
            cube.SetPosition(new Vector3(Position.X, Y, Position.Y));

            HudIcons.Add(new HudIcon() { text = "Open door", texture = RM.GetTexture("opendooricon"), Action = (() => state = DoorState.Opening) });
            HudIcons.Add(new HudIcon() { text = "Close door", texture = RM.GetTexture("closedooricon"), Action = (() => state = DoorState.Closing) });

            HudIcons.Add(new HudIcon() { text = "Lock/unlock", texture = RM.GetTexture("lockicon"), Action = (() => Locked = !Locked) });
            HudIcons.Add(new HudIcon() { text = "Toggle AI", texture = RM.GetTexture("dooraiicon"), Action = (() => ai = !ai) });
        }
Beispiel #31
0
        static void Main(string[] args)
        {
            Window window = new Window(1024, 768, "Aiv.Fast3D Perspective Test", false, 24, 0);

            window.SetDefaultOrthographicSize(10);
            //Window window = new Window("Aiv.Fast3D Perspective Test", 24, 4);



            window.EnableDepthTest();
            //window.CullBackFaces();

            window.SetCursor(false);

            PerspectiveCamera camera = new PerspectiveCamera(new Vector3(0, 6, 30), new Vector3(-10, 180, 0), 60, 0.01f, 1000);

            Texture crate = new Texture("Assets/crate.jpg");

            Texture floorTexture = new Texture("Assets/floor.jpg");

            floorTexture.SetRepeatX();
            floorTexture.SetRepeatY();

            Texture stormTrooperTexture = new Texture("Assets/Stormtrooper.png");

            stormTrooperTexture.SetRepeatX();
            stormTrooperTexture.SetRepeatY();

            Cube cube = new Cube();

            Cube floor = new Cube();

            floor.Scale3    = new Vector3(150, 50f, 150);
            floor.Position3 = new Vector3(0, -25, 0);

            // tiling texture
            for (int i = 0; i < floor.uv.Length; i++)
            {
                floor.uv[i] *= 10;
            }
            floor.UpdateUV();

            Mesh3 stormTrooper = ObjLoader.Load("Assets/Stormtrooper.obj", Vector3.One)[0];

            //stormTrooper.RegenerateNormals();

            Pyramid pyramid = new Pyramid();

            Texture logoAiv = new Texture("Assets/LogoAIV.png");
            Sprite  logo    = new Sprite(1 * logoAiv.Ratio, 1);

            Camera hudCamera = new Camera();

            logo.Camera = hudCamera;

            float lightRotation = -30;


            DepthTexture shadowTexture = new DepthTexture(4096, 4096, 24);

            Sprite shadow = new Sprite(5, 5);

            shadow.Camera = hudCamera;

            float shadow_left   = -30;
            float shadow_right  = 30;
            float shadow_bottom = -30;
            float shadow_top    = 30;
            float shadow_near   = -30;
            float shadow_far    = 30;

            DirectionalLight directionalLight = new DirectionalLight(Utils.EulerRotationToDirection(new Vector3(lightRotation, 180, 0)));

            directionalLight.SetShadowProjection(shadow_left, shadow_right, shadow_bottom, shadow_top, shadow_near, shadow_far);

            //directionalLight.Color = new Vector3(0.5f, 1, 0.5f);

            float crateRotation = 0;

            Mesh3[] botMesh = FbxLoader.Load("Assets/running.fbx", new Vector3(0.02f, 0.02f, 0.02f));

            SkeletalAnimation[] animations = FbxLoader.LoadAnimations("Assets/running.fbx", new Vector3(0.02f, 0.02f, 0.02f));


            int numFrames = 0;

            Mesh3 movingTrooper = ObjLoader.Load("Assets/Stormtrooper.obj", Vector3.One)[0];

            movingTrooper.Position3 = new Vector3(0, 0, 2);

            foreach (SkeletalAnimation animation in animations)
            {
                Console.WriteLine(animation.Name);
                foreach (string subject in animation.KeyFrames.Keys)
                {
                    Console.WriteLine(subject);
                    int currentFrames = 0;
                    foreach (SkeletalAnimation.KeyFrame frame in animation.KeyFrames[subject])
                    {
                        Console.WriteLine(frame.Time + " " + frame.Position + " " + frame.Rotation + " " + frame.Scale);
                        currentFrames++;
                    }
                    if (currentFrames > numFrames)
                    {
                        numFrames = currentFrames;
                    }
                }
            }

            float neckRotation = 0;

            int   animationIndex = 0;
            float animationTimer = 1f / animations[0].Fps;

            movingTrooper.SetParent(cube);

            Mesh3[] tank         = ObjLoader.Load("Assets/T34.obj", Vector3.One);
            Texture tankDiffuse  = new Texture("Assets/T-34.png");
            Texture tankSpecular = new Texture("Assets/T-34_S.png");



            //window.AddPostProcessingEffect(new DepthViewer());

            window.AddPostProcessingEffect(new Fog());

            //window.AddPostProcessingEffect(new Sobel());

            Vector3 pyramidRotation = Vector3.Zero;

            PostProcessingEffect fxaa = window.AddPostProcessingEffect(new FXAA());

            Plane plane = new Plane();

            Vector3 shadowOffset = new Vector3(0, 0, 0.22f);

            Sphere  sphere = new Sphere();
            Texture world  = new Texture("Assets/world.jpg");

            while (window.IsOpened)
            {
                if (window.GetKey(KeyCode.Esc))
                {
                    break;
                }

                if (window.GetKey(KeyCode.W))
                {
                    camera.Position3 += camera.Forward * 10 * window.deltaTime;
                }

                if (window.GetKey(KeyCode.S))
                {
                    camera.Position3 += -camera.Forward * 10 * window.deltaTime;
                }

                if (window.GetKey(KeyCode.D))
                {
                    camera.Position3 += camera.Right * 10 * window.deltaTime;
                }

                if (window.GetKey(KeyCode.A))
                {
                    camera.Position3 += -camera.Right * 10 * window.deltaTime;
                }

                if (window.GetKey(KeyCode.Up))
                {
                    camera.Position3 += camera.Up * 10 * window.deltaTime;
                }

                if (window.GetKey(KeyCode.Down))
                {
                    camera.Position3 += -camera.Up * 10 * window.deltaTime;
                }

                if (window.HasFocus)
                {
                    // currently broken, the mouse is too flaky
                    //float yaw = MouseX(window) * (90 + 45f);
                    //float pitch = MouseY(window) * 90f;
                    //camera.EulerRotation3 += new Vector3(pitch, yaw, 0) * window.deltaTime;
                }

                if (window.GetKey(KeyCode.Right))
                {
                    camera.EulerRotation3 += new Vector3(0, 90 + 45, 0) * window.deltaTime;
                }

                if (window.GetKey(KeyCode.Left))
                {
                    camera.EulerRotation3 -= new Vector3(0, 90 + 45, 0) * window.deltaTime;
                }

                if (window.GetKey(KeyCode.P))
                {
                    camera.EulerRotation3 += new Vector3(90 + 45, 0, 0) * window.deltaTime;
                }

                if (window.GetKey(KeyCode.L))
                {
                    camera.EulerRotation3 -= new Vector3(90 + 45, 0, 0) * window.deltaTime;
                }


                //fxaa.enabled = window.GetKey(KeyCode.X);

                if (window.GetKey(KeyCode.Num1))
                {
                    shadowOffset += Vector3.UnitX * 2 * window.deltaTime;
                    Console.WriteLine(shadowOffset);
                }

                if (window.GetKey(KeyCode.Num2))
                {
                    shadowOffset -= Vector3.UnitX * 2 * window.deltaTime;
                    Console.WriteLine(shadowOffset);
                }

                if (window.GetKey(KeyCode.Num3))
                {
                    shadowOffset += Vector3.UnitY * 2 * window.deltaTime;
                    Console.WriteLine(shadowOffset);
                }

                if (window.GetKey(KeyCode.Num4))
                {
                    shadowOffset -= Vector3.UnitY * 2 * window.deltaTime;
                    Console.WriteLine(shadowOffset);
                }

                if (window.GetKey(KeyCode.Num5))
                {
                    shadowOffset += Vector3.UnitZ * 0.2f * window.deltaTime;
                    Console.WriteLine(shadowOffset);
                }

                if (window.GetKey(KeyCode.Num6))
                {
                    shadowOffset -= Vector3.UnitZ * 2 * window.deltaTime;
                    Console.WriteLine(shadowOffset);
                }



                directionalLight.SetShadowProjection(shadow_left, shadow_right, shadow_bottom, shadow_top, shadow_near, shadow_far);

                animationTimer -= window.deltaTime;
                if (animationTimer <= 0)
                {
                    animationIndex++;
                    if (animationIndex >= numFrames)
                    {
                        animationIndex = 0;
                    }
                    animationTimer = 1f / animations[0].Fps;
                }

                foreach (string subject in animations[0].KeyFrames.Keys)
                {
                    if (botMesh[0].HasBone(subject))
                    {
                        Mesh3.Bone bone = botMesh[0].GetBone(subject);
                        if (animationIndex < animations[0].KeyFrames[subject].Count)
                        {
                            //bone.Position = animations[0].KeyFrames[subject][animationIndex].Position;
                            //bone.Rotation = animations[0].KeyFrames[subject][animationIndex].Rotation;
                        }
                    }
                }

                pyramidRotation += new Vector3(0, 10, 0) * window.deltaTime;
                neckRotation    += window.deltaTime;

                string boneName = "mixamorig:Neck";
                if (botMesh[0].HasBone(boneName))
                {
                    Mesh3.Bone bone = botMesh[0].GetBone(boneName);
                    bone.Rotation = Quaternion.FromEulerAngles(new Vector3(0, (float)Math.Sin(neckRotation) / 2, 0));
                }

                if (botMesh[1].HasBone(boneName))
                {
                    Mesh3.Bone bone = botMesh[1].GetBone(boneName);
                    bone.Rotation = Quaternion.FromEulerAngles(new Vector3(0, (float)Math.Sin(neckRotation) / 2, 0));
                }



                crateRotation += 30 * window.deltaTime;

                //lightRotation += 10 * window.deltaTime;
                //directionalLight.UpdateDirection(Utils.EulerRotationToDirection(new Vector3(lightRotation, 180, 0)));

                window.DisableCullFaces();
                // draw shadow map texture
                window.RenderTo(shadowTexture);
                window.CullFrontFaces();
                floor.DrawShadowMap(directionalLight);
                pyramid.Scale3         = new Vector3(1, 2, 1);
                pyramid.EulerRotation3 = pyramidRotation;
                pyramid.Position3      = new Vector3(-6, 2, 10) + shadowOffset;
                pyramid.DrawShadowMap(directionalLight);

                pyramid.Scale3    = new Vector3(1, 2, 1);
                pyramid.Rotation3 = Vector3.Zero;
                pyramid.Position3 = new Vector3(-30, 2, 10) + shadowOffset;
                pyramid.DrawShadowMap(directionalLight);


                botMesh[0].Position3 = new Vector3(6, 0, 10) + shadowOffset;
                botMesh[0].DrawShadowMap(directionalLight);
                botMesh[1].Position3 = new Vector3(6, 0, 10) + shadowOffset;
                botMesh[1].DrawShadowMap(directionalLight);

                stormTrooper.Position3 = new Vector3(0, 0, 5) + shadowOffset;
                stormTrooper.Rotation3 = Vector3.Zero;
                stormTrooper.DrawShadowMap(directionalLight);
                stormTrooper.Position3 = new Vector3(-5, 0, 5) + shadowOffset;
                stormTrooper.Rotation3 = Vector3.Zero;
                stormTrooper.DrawShadowMap(directionalLight);
                stormTrooper.Position3 = new Vector3(7, 0, 5) + shadowOffset;
                stormTrooper.Rotation3 = Utils.LookAt((camera.Position3 - stormTrooper.Position3).Normalized());
                stormTrooper.DrawShadowMap(directionalLight);
                cube.EulerRotation3 = new Vector3(0, crateRotation, 0);
                cube.Position3      = new Vector3(0, 7, 0) + shadowOffset;
                cube.DrawShadowMap(directionalLight);
                cube.EulerRotation3 = Vector3.Zero;
                cube.Position3      = new Vector3(5, 1, 5) + shadowOffset;
                cube.DrawShadowMap(directionalLight);


                foreach (Mesh3 item in tank)
                {
                    item.Position3 = new Vector3(-10, 0, 20) + shadowOffset;
                    item.DrawShadowMap(directionalLight);
                }

                window.DisableCullFaces();
                window.RenderTo(null);

                window.CullBackFaces();
                //window.DisableCullFaces();

                floor.DrawPhong(floorTexture, directionalLight, new Vector3(0.5f, 0.5f, 0.5f), 0, shadowTexture);

                pyramid.Scale3         = new Vector3(1, 2, 1);
                pyramid.EulerRotation3 = pyramidRotation;
                pyramid.Position3      = new Vector3(-6, 2, 10);
                pyramid.DrawGouraud(new Vector4(1, 0, 0, 1), directionalLight, shadowTexture);

                pyramid.Scale3         = new Vector3(1, 2, 1);
                pyramid.EulerRotation3 = Vector3.Zero;
                pyramid.Position3      = new Vector3(-30, 2, 10);
                pyramid.DrawGouraud(new Vector4(1, 1, 0, 1), directionalLight, shadowTexture);

                botMesh[0].Position3 = new Vector3(6, 0, 10);
                botMesh[0].DrawGouraud(new Vector4(0, 0.8f, 1, 1), directionalLight, shadowTexture, 0.01f);
                botMesh[1].Position3 = new Vector3(6, 0, 10);
                botMesh[1].DrawGouraud(new Vector4(1, 0, 0, 1), directionalLight, shadowTexture, 0.01f);

                stormTrooper.Position3 = new Vector3(0, 0, 5);
                stormTrooper.Rotation3 = Vector3.Zero;
                stormTrooper.DrawGouraud(stormTrooperTexture, directionalLight, shadowTexture);

                stormTrooper.Position3 = new Vector3(-5, 0, 5);
                stormTrooper.Rotation3 = Vector3.Zero;
                stormTrooper.DrawPhong(stormTrooperTexture, directionalLight, new Vector3(0, 0.1f, 0), 0.75f, shadowTexture);

                stormTrooper.Position3 = new Vector3(7, 0, 5);
                stormTrooper.Rotation3 = Utils.LookAt((camera.Position3 - stormTrooper.Position3).Normalized());
                stormTrooper.DrawCel(stormTrooperTexture, directionalLight, new Vector3(0, 0.1f, 0), 0.75f, shadowTexture);


                //cube.DrawColor(new Vector4(1, 0, 0, 1));
                cube.EulerRotation3 = new Vector3(0, crateRotation, 0);
                cube.Position3      = new Vector3(0, 7, 0);
                cube.DrawTexture(crate);

                if (window.GetKey(KeyCode.Space))
                {
                    movingTrooper.Position3 += movingTrooper.Forward * window.deltaTime * 2;
                }

                if (window.GetKey(KeyCode.G))
                {
                    movingTrooper.EulerRotation3 += new Vector3(0, 90, 0) * window.deltaTime;
                }

                if (window.GetKey(KeyCode.H))
                {
                    movingTrooper.EulerRotation3 -= new Vector3(0, 90, 0) * window.deltaTime;
                }

                movingTrooper.DrawGouraud(new Vector4(1, 0, 0, 1), directionalLight);

                cube.EulerRotation3 = Vector3.Zero;
                cube.Position3      = new Vector3(5, 1, 5);
                cube.DrawGouraud(new Vector4(0, 0, 1, 1), directionalLight, shadowTexture);


                foreach (Mesh3 item in tank)
                {
                    item.Position3 = new Vector3(-10, 0, 20);
                    item.DrawPhong(tankDiffuse, directionalLight, new Vector3(0.1f, 0.1f, 0.1f), tankSpecular);
                }

                plane.Position3       = new Vector3(-13, 5, 0);
                plane.EulerRotation3 += Vector3.UnitY * 30 * window.deltaTime;
                plane.DrawColor(new Vector4(1, 1, 0, 1));

                sphere.Position3       = new Vector3(-5, 2, 20);
                sphere.EulerRotation3 += Vector3.UnitY * 10 * window.deltaTime;
                sphere.Scale3          = new Vector3(3);
                sphere.DrawPhong(world, directionalLight, new Vector3(0.2f, 0.2f, 0.2f));
                //sphere.DrawColor(new Vector4(1, 0, 0, 1));

                logo.DrawTexture(logoAiv);

                shadow.DrawTexture(shadowTexture);

                // this ensure postprocessing works
                window.DisableCullFaces();

                plane.Position3       = new Vector3(-10, 5, 0);
                plane.EulerRotation3 += Vector3.UnitY * 30 * window.deltaTime;
                plane.DrawColor(new Vector4(0, 1, 1, 1));

                window.Update();
            }
        }
    // Update is called once per frame
    void Update()
    {
        if (opening)
        {
            Player_scripts.score = 0;
            text.text            = "SELECT LEVEL ○easy ×normal PRESS ANY BUTTON";
            Light.SetActive(false);
            Sword.SetActive(false);
            Player.SetActive(false);
            EnemyMaster.SetActive(false);
            Enemy0.SetActive(false);
            Enemy1.SetActive(false);
            Unitychan.SetActive(true);
            Cube.SetActive(false);

            if (_TimeCount + _Opening_Time < Time.time)
            {
                //rb.velocity = Vector3.zero;
                //animator.SetBool("Stop", true);
                Cube.SetActive(true);
                // ボタンイベント UnityのInput.GetButtonと同じ仕組み
                if (Input.GetKey("up"))
                {
                    _TimeCount = Time.time;
                    opening    = false;
                    countdown  = true;
                    NormalSpeed();
                }
                Debug.Log("Success");
                if (Input.GetKey("down"))
                {
                    _TimeCount = Time.time;
                    opening    = false;
                    countdown  = true;
                    HighSpeed();
                }
            }
            else
            {
                Unitychan.transform.position += transform.forward * 0.035f;
                animator.SetBool("Stop", false);
            }
        }
        if (countdown)
        {
            Light.SetActive(false);
            Sword.SetActive(false);
            Player.SetActive(false);
            EnemyMaster.SetActive(false);
            Enemy0.SetActive(false);
            Enemy1.SetActive(false);
            Unitychan.SetActive(false);
            Cube.SetActive(true);
            if (_TimeCount + _Countdown_Time1 > Time.time)
            {
                text.text = "3";
            }
            else if (_TimeCount + _Countdown_Time2 > Time.time)
            {
                text.text = "2";
            }
            else if (_TimeCount + _Countdown_Time3 > Time.time)
            {
                text.text = "1";
            }
            else
            {
                countdown  = false;
                playing    = true;
                _TimeCount = Time.time;
                Light.SetActive(false);
                Sword.SetActive(true);
                Unitychan.SetActive(false);
                Cube.SetActive(false);
                Player.SetActive(true);
                Player_scripts.Set();
                Enemy0.SetActive(true);
                Enemy0_scripts.Set();
                Enemy1.SetActive(true);
                Enemy1_scripts.Set();
                EnemyMaster.SetActive(true);
                Player_scripts.Move();
                Camera_scripts.Move();
                Light_scripts.Move();
                Sword_scripts.Move();
            }
        }


        if (playing)
        {
            if (Input.GetKey("up"))
            {
                Debug.Log("Circle Down");
                Light.SetActive(true);
                Sword.SetActive(false);
            }
            Debug.Log("Success");
            if (Input.GetKey("down"))
            {
                Debug.Log("Circle UP");
                Light.SetActive(false);
                Sword.SetActive(true);
            }
        }

        if (gameover)
        {
            if (_TimeCount + _Gameover_Time < Time.time)
            {
                ReStart();
                this.gameover = true;
                Light.SetActive(false);
                Sword.SetActive(false);
                Player.SetActive(false);
                EnemyMaster.SetActive(true);
                Enemy0.SetActive(false);
                Enemy1.SetActive(false);
                Unitychan.SetActive(false);
                Cube.SetActive(true);
                text.text = "Score " + Player_scripts.score + "press ○ to ReStart";

                if (Input.GetKey("up"))
                {
                    Opening();
                    _TimeCount = Time.time;
                    UnityChan_scripts.ReStart();
                    Light.SetActive(false);
                    Sword.SetActive(false);
                    Player.SetActive(false);
                    EnemyMaster.SetActive(false);
                    Enemy0.SetActive(false);
                    Enemy1.SetActive(false);
                    Unitychan.SetActive(true);
                    Cube.SetActive(false);
                    Enemy0_scripts.ReStart();
                }
            }
        }
    }
Beispiel #33
0
    public void GenerateMap()
    {
        manager = FindObjectOfType <GameManager>();
        // Reinitialisation de la map
        while (transform.childCount > 0)
        {
            DestroyImmediate(transform.GetChild(0).gameObject);
        }
        GameObject watter = Instantiate(baseWatter, new Vector3(WIDTH / 2.0f - 0.5f, -0.1f, WIDTH / 2.0f - 0.5f), Quaternion.identity, transform);
        GameObject floor  = Instantiate(baseFloor, new Vector3(WIDTH / 2.0f - 0.5f, -1, WIDTH / 2.0f - 0.5f), Quaternion.identity, transform);

        watter.transform.localScale    = new Vector3(WIDTH - 0.1f, 0.8f, WIDTH - 0.1f);
        floor.transform.localScale     = new Vector3(WIDTH, 1f, WIDTH);
        Camera.main.transform.position = new Vector3(WIDTH / 2, Camera.main.transform.position.y, WIDTH / 2);
        cubes = new Cube[WIDTH * WIDTH];
        for (int x = 0; x < WIDTH; ++x)
        {
            for (int z = 0; z < WIDTH; ++z)
            {
                GameObject goCube = Instantiate(defaultCube.gameObject, new Vector3(x, 0, z), Quaternion.identity, transform);
                Cube       cube   = goCube.GetComponent <Cube>();
                SetCube(x, z, cube);
                cube.SetPosition(x, z);
            }
        }

        // Création des cubes de base
        List <Cube> toTreat     = new List <Cube>();
        List <Cube> treats      = new List <Cube>();
        float       totalWeight = TypeWeight();

        for (int i = 0; i < nbBaseCube; ++i)
        {
            Cube  cube  = GetCube(Random.Range(0, WIDTH), Random.Range(0, WIDTH));
            float rand  = Random.value;
            int   index = -1;
            while (rand >= 0 && index < cubeType.Count)
            {
                ++index;
                rand -= cubeType[index].weight / totalWeight;
            }

            cube = ChangeCube(cube, cubeType[index].type);
            toTreat.Add(cube);
        }

        // Propagation des cubes de base
        while (toTreat.Count > 0)
        {
            List <Cube> next = new List <Cube>();
            foreach (Cube treat in toTreat)
            {
                treat.AddDecoration();
                int x = (int)treat.position.x;
                int y = (int)treat.position.y;
                if (x > 0 && GetCube(x - 1, y).type == Cube.Type.none)
                {
                    next.Add(ChangeCube(GetCube(x - 1, y), treat.type));
                }
                if (x < WIDTH - 1 && GetCube(x + 1, y).type == Cube.Type.none)
                {
                    next.Add(ChangeCube(GetCube(x + 1, y), treat.type));
                }
                if (y > 0 && GetCube(x, y - 1).type == Cube.Type.none)
                {
                    next.Add(ChangeCube(GetCube(x, y - 1), treat.type));
                }
                if (y < WIDTH - 1 && GetCube(x, y + 1).type == Cube.Type.none)
                {
                    next.Add(ChangeCube(GetCube(x, y + 1), treat.type));
                }
            }
            toTreat = next;
            next    = new List <Cube>();
        }
        for (int i = 0; i < manager.mobsType.Count; ++i)
        {
            for (int n = 0; n < ((manager.mobsType[i].alimentation == Mob.Alimentation.carnivore)?3:5); ++n)
            {
                do
                {
                    Cube c = GetCube(Random.Range(0, WIDTH), Random.Range(0, WIDTH));
                    if (c.type != Cube.Type.watter && c.OnSurface == null)
                    {
                        Mob m = Instantiate(manager.mobsType[i], new Vector3(c.position.x, 1, c.position.y), Quaternion.identity, transform);
                        m.pos = c;
                        manager.mobs.Add(m);
                        break;
                    }
                } while (true);
            }
        }
    }
Beispiel #34
0
 private void Start()
 {
     parent = transform.parent.GetComponent <Cube>();
     core   = parent.transform.GetComponentInParent <Core>();
 }
Beispiel #35
0
 protected virtual void OnCombine(Cube owner, Cube target)
 {
 }
Beispiel #36
0
        public void ForceFieldShapes()
        {
            var unitPos = new Vector3(0, 0, 0);
            var unitRot = new Quaternion(0, 0, 0, 1);
            var unitScl = new Vector3(1, 1, 1);

            Vector3 alongAxis;
            Vector3 aroundAxis;
            Vector3 awayAxis;

            float falloff;

            // Sphere
            var shapeSphere = new Sphere();

            shapeSphere.PreUpdateField(unitPos, unitRot, unitScl);

            falloff = shapeSphere.GetDistanceToCenter(new Vector3(0.1f, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0.1f, falloff);
            Assert.Equal(new Vector3(0, 1, 0), alongAxis);
            Assert.Equal(new Vector3(0, 0, -1), aroundAxis);
            Assert.Equal(new Vector3(1, 0, 0), awayAxis);

            falloff = shapeSphere.GetDistanceToCenter(new Vector3(0.5f, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0.5f, falloff);
            Assert.Equal(new Vector3(0, 1, 0), alongAxis);
            Assert.Equal(new Vector3(0, 0, -1), aroundAxis);
            Assert.Equal(new Vector3(1, 0, 0), awayAxis);

            falloff = shapeSphere.GetDistanceToCenter(new Vector3(1, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1f, falloff);
            Assert.Equal(new Vector3(0, 1, 0), alongAxis);
            Assert.Equal(new Vector3(0, 0, -1), aroundAxis);
            Assert.Equal(new Vector3(1, 0, 0), awayAxis);

            // Box
            var shapeBox = new Cube();

            shapeBox.PreUpdateField(unitPos, unitRot, unitScl);

            falloff = shapeBox.GetDistanceToCenter(new Vector3(0.3f, 0, 0.4f), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0.4f, falloff); // Bigger than the two
            Assert.Equal(new Vector3(0, 1, 0), alongAxis);
            Assert.Equal(new Vector3(0.8f, 0, -0.6f), aroundAxis);
            Assert.Equal(new Vector3(0.6f, 0, 0.8f), awayAxis);

            falloff = shapeBox.GetDistanceToCenter(new Vector3(0.5f, 0, 0.4f), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0.5f, falloff);
            Assert.Equal(new Vector3(0, 1, 0), alongAxis);

            falloff = shapeBox.GetDistanceToCenter(new Vector3(1, 0, 0.4f), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1f, falloff);
            Assert.Equal(new Vector3(0, 1, 0), alongAxis);

            // Cylinder
            var shapeCylinder = new Cylinder();

            shapeCylinder.PreUpdateField(unitPos, unitRot, unitScl);

            falloff = shapeCylinder.GetDistanceToCenter(new Vector3(0, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0, falloff);

            falloff = shapeCylinder.GetDistanceToCenter(new Vector3(0, 0.5f, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0, falloff); // No falloff along the Y-axis

            falloff = shapeCylinder.GetDistanceToCenter(new Vector3(0, 1, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1, falloff);

            falloff = shapeCylinder.GetDistanceToCenter(new Vector3(0.5f, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0.5f, falloff);

            falloff = shapeCylinder.GetDistanceToCenter(new Vector3(1, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1f, falloff);

            // Torus
            var shapeTorus = new Torus();

            shapeTorus.PreUpdateField(unitPos, unitRot, unitScl);

            falloff = shapeTorus.GetDistanceToCenter(new Vector3(0, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1, falloff); // This is actually outside the torus

            falloff = shapeTorus.GetDistanceToCenter(new Vector3(0.5f, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1, falloff); // This is on the torus surface, inner circle
            Assert.Equal(new Vector3(0, 0, -1), alongAxis);
            Assert.Equal(new Vector3(-1, 0, 0), awayAxis);
            Assert.Equal(new Vector3(0, 1, 0), aroundAxis);

            falloff = shapeTorus.GetDistanceToCenter(new Vector3(1, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(0, falloff); // This is on the torus axis
            Assert.Equal(new Vector3(0, 0, -1), alongAxis);

            falloff = shapeTorus.GetDistanceToCenter(new Vector3(1.5f, 0, 0), new Vector3(0, 1, 0), out alongAxis, out aroundAxis, out awayAxis);
            Assert.Equal(1, falloff); // This is on the torus surface, outer circle
            Assert.Equal(new Vector3(0, 0, -1), alongAxis);
            Assert.Equal(new Vector3(1, 0, 0), awayAxis);
            Assert.Equal(new Vector3(0, -1, 0), aroundAxis);
        }
Beispiel #37
0
        //Purpose: To Process Information when Enter has been clicked
        //Requires: The user to click enter and the shape previously entered
        //Returns: none
        private void Enter_Click(object sender, EventArgs e)
        {
            try {
                // get the coordinates for the first point
                firstX = Double.Parse(pointBox1.Text);
                firstY = Double.Parse(pointBox2.Text);

                switch (shapeName)
                {
                case "circle":
                {
                    enteredRadius = Double.Parse(pointBox3.Text);
                    Circle circle = new Circle(enteredRadius, firstX, firstY, 0, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = circle.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                }
                break;

                case "square":

                    secX = Double.Parse(pointBox3.Text);
                    Square square = new Square(firstX, firstY, secX, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = square.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                    break;

                case "rectangle":
                    secX = Double.Parse(pointBox3.Text);
                    secY = Double.Parse(pointBox4.Text);
                    ShapesLibrary.Rectangle rectangle = new ShapesLibrary.Rectangle(firstX, firstY, secX, secY, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = rectangle.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                    break;

                case "cube":
                    secX = Double.Parse(pointBox3.Text);
                    Cube cube = new Cube(firstX, firstY, secX, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = cube.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                    break;

                case "cylinder":
                    enteredRadius = Double.Parse(pointBox3.Text);
                    height        = Double.Parse(pointBox4.Text);
                    Cylinder cylinder = new Cylinder(enteredRadius, firstX, firstY, height, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = cylinder.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                    break;

                case "sphere":
                    enteredRadius = Double.Parse(pointBox3.Text);
                    Sphere sphere = new Sphere(enteredRadius, firstX, firstY, 0, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = sphere.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                    break;

                case "cuboid":
                    enteredWidth = Double.Parse(pointBox3.Text);
                    height       = Double.Parse(pointBox4.Text);
                    Cuboid cuboid = new Cuboid(firstX, firstY, enteredWidth, height, shapeName);
                    // use ToString to output to the output boxes
                    OutputLabel1.Text = cuboid.ToString();
                    // show the associated picture
                    displayPicture(shapeName);
                    break;

                default:
                    OutputLabel1.Visible = true;
                    OutputLabel1.Text    = String.Format("Invalid Choice!");
                    break;
                }
            }
            catch (NegativeNumberException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (FormatException f)
            {
                MessageBox.Show(" Please fill in all the information needed.");
            }
            pointBox1.Clear();
            pointBox2.Clear();
            pointBox3.Clear();
            pointBox4.Clear();
        }
 virtual public void Init(Cube cb)
 {
 }
Beispiel #39
0
        public static void SolidTestRender(int spp)
        {
            Console.WriteLine("Loading file...");
            var filePath = Path.Combine(GetExecutionPath(), "neon_env.ppm");

            //var filePath = Path.Combine(GetExecutionPath(), "winter_river_1k.ppm");
            Console.WriteLine("Parsing file...");
            var textureCanvas = PPM.ParseFile(filePath);
            var image         = new UVImage(textureCanvas);
            var map           = new TextureMap(image, UVMapping.Spherical);

            var skySphere = new Sphere
            {
                Material =
                {
                    Texture       = map,            Ambient = 1.0f, CastsShadows = false, Transparency = 0f, Roughness = 1f,
                    SpecularColor = new Color(0.0f, 0.0f, 0.0f)
                }
            };

            skySphere.SetTransform(Transform.RotateY(3.3f).Scale(1000f));

            var radius = 0.25f;
            var red    = new Material {
                Texture = new SolidColor(new Color(1, 0, 0)), Reflective = 0.3f, Roughness = 0.3f, Ambient = 0.0f, Metallic = 0.3f, SpecularColor = new Color(0.3f, 0.3f, 0.3f)
            };
            var blue = new Material {
                Texture = new SolidColor(new Color(0, 0, 1)), Reflective = 0.3f, Roughness = 0.3f, Ambient = 0.0f, Metallic = 0.3f, SpecularColor = new Color(0.3f, 0.3f, 0.3f)
            };
            var yellow = new Material {
                Texture = new SolidColor(new Color(1, 1, 0)), Reflective = 0.3f, Roughness = 0.3f, Ambient = 0.0f, Metallic = 0.3f, SpecularColor = new Color(0.3f, 0.3f, 0.3f)
            };
            var white = new Material {
                Texture = new SolidColor(new Color(1, 1, 1)), Reflective = 0.3f, Roughness = 0.3f, Ambient = 0.0f, Metallic = 0.3f, SpecularColor = new Color(0.3f, 0.3f, 0.3f)
            };
            var blackPip = new Material {
                Texture = new SolidColor(new Color(0.1f, 0.1f, 0.1f)), Ambient = 0.0f, Roughness = 0.8f, Metallic = 0f, SpecularColor = new Color(0.2f, 0.2f, 0.2f)
            };
            var whitePip = new Material {
                Texture = new SolidColor(new Color(0.95f, 0.95f, 0.95f)), Ambient = 0.0f, Roughness = 0.8f, Metallic = 0f, SpecularColor = new Color(0.2f, 0.2f, 0.2f)
            };

            var d1 = CutPips(RoundedCube(radius, blue), whitePip);
            var d2 = CutPips(RoundedCube(radius, red), whitePip);
            var d3 = CutPips(RoundedCube(radius, white), blackPip);
            var d4 = CutPips(RoundedCube(radius, yellow), blackPip);

            d1.SetTransform(Transform.RotateY(-2.2f).TranslateY(1f).Scale(0.5f));
            d2.SetTransform(Transform.RotateZ(MathF.PI / 2f).TranslateY(1f).TranslateX(2f).TranslateZ(1f).Scale(0.5f));
            d3.SetTransform(Transform.RotateY(0.5f).TranslateY(1f).TranslateX(-4f).TranslateZ(1f).Scale(0.5f));
            d4.SetTransform(Transform.RotateY(-0.2f).TranslateY(3f).TranslateX(0.2f).TranslateZ(1.25f).Scale(0.5f));

            var lightGray = new Color(0.48f, 0.48f, 0.48f);
            var darkGray  = new Color(0.15f, 0.15f, 0.15f);
            //var s1 = new StripeTexture(lightGray, darkGray);
            //var s2 = new StripeTexture(lightGray, darkGray);
            //s2.SetTransform(Transforms.RotateY(MathF.PI / 2));
            //var pattern = new BlendedCompositeTexture(s1, s2);
            //pattern.SetTransform(Transforms.Scale(1f / 20f));

            var pattern = new CheckerTexture(lightGray, darkGray);

            pattern.SetTransform(Transform.Scale(1f / 20f));

            var floor = new Cube
            {
                Material =
                {
                    Texture       = pattern,
                    Roughness     =           0.5f,
                    Specular      =           0.1f,
                    Diffuse       =           0.3f,
                    Reflective    =          0.15f,
                    SpecularColor = new Color(0.3f, 0.3f, 0.3f),
                    Ambient       = 0f
                }
            };

            floor.SetTransform(Transform.TranslateY(-1f).Scale(20f));
            var g = new Group(d1, d2, d3, d4, floor, skySphere);

            g.Divide(1);

            var w = new World();

            w.SetLights(new AreaLight(new Point(-8, 10, -10), new Vector(12f, 0, 0), 6, new Vector(0, 0f, -10f), 3,
                                      new Color(1.1f, 1.1f, 1.1f), new Sequence(0.7f, 0.3f, 0.9f, 0.1f, 0.5f)));
            //w.SetLights(new PointLight(new Point(-8, 10, -10), new Color(0.9f, 0.9f, 0.9f)));
            //w.SetLights(new AreaLight(new Point(-3, 6, -4), new Vector(1f, 0, 0), 3, new Vector(0, 1f, 0), 3,
            //                          new Color(1.4f, 1.4f, 1.4f), new Sequence(0.7f, 0.3f, 0.9f, 0.1f, 0.5f)));
            //w.SetLights(new AreaLight(new Point(-10, 10, -10), new Vector(1,0,0), 4, new Vector(0,1,0), 3, Colors.White));
            w.SetObjects(g);

            //var width = 600;
            //var height = 400;
            //var transform = Transforms.View(new Point(0, 1.5f, -5f), new Point(0, 1, 0), new Vector(0, 1, 0));
            //var c = new PinholeCamera(transform, MathF.PI / 3f, width, height);
            //var ws = new ComposableWorldShading(2, GGXNormalDistribution.Instance, SchlickBeckmanGeometricShadow.Instance, SchlickFresnelFunction.Instance, w);
            ////var ws = new PhongWorldShading(2, w);
            //var scene = new Scene(c, ws);
            ////var aaa = new AdaptiveRenderer(2, 0.01f, scene);
            //var aaa = new SamplesPerPixelRenderer(24, scene);
            //var canvas = new Canvas(width, height);

            var width  = 600;
            var height = 400;
            var from   = new Point(0, 1.5f, -5f);
            var to     = new Point(0, 1, -0.5f);

            var canvas = new Canvas(width, height);

            var pps         = new PerPixelSampler(spp);
            var fov         = MathF.PI / 3f;
            var aspectRatio = (float)width / height;
            var camera      = new ApertureCamera(fov, aspectRatio, 0.15f, from, to, Vectors.Up);
            //var transform = Transforms.View(from, to, new Vector(0, 1, 0));
            //var camera = new PinholeCamera2(transform, fov, aspectRatio);
            //var cws = new PhongWorldShading2(4, w);
            var cws = new ComposableWorldSampler(2,
                                                 4,
                                                 GGXNormalDistribution.Instance,
                                                 SchlickBeckmanGeometricShadow.Instance,
                                                 SchlickFresnelFunction.Instance,
                                                 w);

            var ctx = new RenderContext(canvas, new RenderPipeline(cws, camera, pps));

            Console.WriteLine("Rendering at {0}x{1}...", width, height);
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            ctx.Render();
            // RenderContext.Render(canvas, aaa);
            PPM.ToFile(canvas, Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "solid");
            stopwatch.Stop();
            Console.WriteLine("Done ({0})", stopwatch.Elapsed);
        }
 virtual public void OnRelaseTouch(Cube b)
 {
     TouchController.getInstance().OnRelaseTouch(b);
 }
    public void exec()
    {
        Cube cube = GameObject.Find("cube").GetComponent <Cube>();

        cube.StartOver();
    }
Beispiel #42
0
 public Unit_Attack_(Unit owner, List <Cube> attackTargets, Cube centerCube) : base(owner)
 {
     this.attackTargets = attackTargets;
     this.centerCube    = centerCube;
 }
Beispiel #43
0
        public void WriteTwoModelsWithSharedTexture()
        {
            TestContext.CurrentContext.AttachShowDirLink();
            TestContext.CurrentContext.AttachGltfValidatorLinks();

            // get the texture from its original location and save it in our test directory.
            var assetsPath = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Assets");


            var tex1Bytes = System.IO.File.ReadAllBytes(System.IO.Path.Combine(assetsPath, "shannon.png"));
            var tex2Bytes = System.IO.File.ReadAllBytes(System.IO.Path.Combine(assetsPath, "Texture1.jpg"));

            var tex1 = tex1Bytes.AttachToCurrentTest("shared-shannon.png");
            var tex2 = tex2Bytes.AttachToCurrentTest("subdir\\shared-in-dir-Texture1.jpg");

            // create a material using our shared texture
            var material1 = new MaterialBuilder()
                            .WithUnlitShader()
                            .WithBaseColor(tex1);

            // create a material using our shared texture
            var material2 = new MaterialBuilder()
                            .WithUnlitShader()
                            .WithBaseColor(tex2);

            // create a simple cube mesh
            var mesh1 = new Cube <MaterialBuilder>(material1).ToMesh(Matrix4x4.Identity);
            var mesh2 = new Cube <MaterialBuilder>(material2).ToMesh(Matrix4x4.Identity);
            var scene = new SceneBuilder();

            scene.AddRigidMesh(mesh1, Matrix4x4.CreateTranslation(-2, 0, 0));
            scene.AddRigidMesh(mesh2, Matrix4x4.CreateTranslation(2, 0, 0));

            var gltf = scene.ToGltf2();

            // define the texture sharing hook; this is a pretty naive approach, but it's good
            // enough to demonstrate how it works.

            string imageSharingHook(IO.WriteContext ctx, string uri, Memory.MemoryImage image)
            {
                Assert.IsTrue(new string[] { tex1, tex2 }.Contains(image.SourcePath));

                if (File.Exists(image.SourcePath))
                {
                    // image.SourcePath is an absolute path, we must make it relative to ctx.CurrentDirectory

                    var currDir = ctx.CurrentDirectory.FullName + "\\";

                    // if the shared texture can be reached by the model in its directory, reuse the texture.
                    if (image.SourcePath.StartsWith(currDir, StringComparison.OrdinalIgnoreCase))
                    {
                        // we've found the shared texture!, return the uri relative to the model:
                        return(image.SourcePath.Substring(currDir.Length));
                    }

                    // TODO: Here we could also try to find a texture equivalent to MemoryImage in the
                    // CurrentDirectory even if it has a different name, to minimize texture duplication.
                }

                // we were unable to reuse the shared texture,
                // default to write our own texture.

                image.SaveToFile(Path.Combine(ctx.CurrentDirectory.FullName, uri));

                return(uri);
            }

            var settings = new WriteSettings();

            settings.ImageWriting       = ResourceWriteMode.SatelliteFile;
            settings.ImageWriteCallback = imageSharingHook;

            // save the model several times:

            var path1 = gltf.AttachToCurrentTest("model1.glb", settings);
            var path2 = gltf.AttachToCurrentTest("model2.glb", settings);
            var path3 = gltf.AttachToCurrentTest("model3.gltf", settings);

            var satellites1 = ModelRoot.GetSatellitePaths(path1);
            var satellites2 = ModelRoot.GetSatellitePaths(path2);
            var satellites3 = ModelRoot.GetSatellitePaths(path3);

            Assert.IsTrue(satellites1.Contains("shared-shannon.png"));
            Assert.IsTrue(satellites1.Contains("subdir/shared-in-dir-Texture1.jpg"));

            Assert.IsTrue(satellites2.Contains("shared-shannon.png"));
            Assert.IsTrue(satellites2.Contains("subdir/shared-in-dir-Texture1.jpg"));

            Assert.IsTrue(satellites3.Contains("shared-shannon.png"));
            Assert.IsTrue(satellites3.Contains("subdir/shared-in-dir-Texture1.jpg"));
        }
Beispiel #44
0
 private void Start()
 {
     cube = GameObject.Find("Player Cube").GetComponent <Cube>();
 }
 double ICubeIntersectionVolumeCalculator.Calculate(Cube cubeA, Cube cubeB)
 {
     return(cubeA.Width.Overlap(cubeB.Width)
            * cubeA.Height.Overlap(cubeB.Height)
            * cubeA.Depth.Overlap(cubeB.Depth));
 }
Beispiel #46
0
        public static void SolvePart1(HashSet <Cube> conwayCube)
        {
            Console.WriteLine("\nPart 1 ----------");
            Console.WriteLine("Before any cycles:");
            //OutputHyperCube(cubes);

            int cycles       = 6;
            int currentCycle = 0;

            while (currentCycle < cycles)
            {
                // first let's build all neighbours for our current position
                foreach (var cube in conwayCube.ToList())
                {
                    AddNeighbours(cube, conwayCube);
                }

                // now take a clone of the base set of cubes
                var cubes = CloneConwayCube(conwayCube);
                foreach (var cube in cubes)
                {
                    int activeNeighbourCount = GetActiveNeighbourCount(cube, conwayCube);

                    if (cube.Active && !(activeNeighbourCount == 2 || activeNeighbourCount == 3))
                    {
                        cube.Value = '.';
                    }
                    else if (!cube.Active && activeNeighbourCount == 3)
                    {
                        cube.Value = '#';
                    }
                }

                currentCycle++;
                conwayCube = new HashSet <Cube>(cubes.Where(x => x.Active));
                Console.WriteLine($"After {currentCycle} cycle: {conwayCube.Count(x => x.Active)}");
                //OutputHyperCube(cubes);
            }

            void AddNeighbours(Cube cube, HashSet <Cube> cubes)
            {
                // how to loop all positions
                for (int x = cube.X - 1; x <= cube.X + 1; x++)
                {
                    for (int y = cube.Y - 1; y <= cube.Y + 1; y++)
                    {
                        for (int z = cube.Z - 1; z <= cube.Z + 1; z++)
                        {
                            var neighbour = new Cube(x, y, z);
                            if (neighbour.Equals(cube))
                            {
                                continue;
                            }

                            if (!cubes.Contains(neighbour))
                            {
                                cubes.Add(neighbour);
                            }
                        }
                    }
                }
            }

            int GetActiveNeighbourCount(Cube cube, HashSet <Cube> cubes)
            {
                int count  = 0;
                int checks = 0;

                // how to loop all positions
                for (int x = cube.X - 1; x <= cube.X + 1; x++)
                {
                    for (int y = cube.Y - 1; y <= cube.Y + 1; y++)
                    {
                        for (int z = cube.Z - 1; z <= cube.Z + 1; z++)
                        {
                            checks++;
                            var neighbour = new Cube(x, y, z);
                            if (neighbour.Equals(cube) || !cubes.TryGetValue(neighbour, out Cube ccc))
                            {
                                continue;
                            }

                            if (ccc.Active)
                            {
                                count++;
                            }
                        }
                    }
                }

                return(count);
            }
        }
Beispiel #47
0
    public static Cube MakeCube(int netIndex, IList <List <int> > colors, IList <List <int> > symbols, int baseRotation,
                                bool flipped)
    {
        Cube cube;

        switch (netIndex)
        {
        case 0:
            if (!flipped)
            {
                cube = new Cube(new[] {
                    colors[2][0],
                    colors[4][0],
                    colors[3][0],
                    colors[2][1],
                    colors[1][1],
                    colors[0][1],
                }, new[] {
                    symbols[2][0],
                    symbols[4][0],
                    symbols[3][0],
                    symbols[2][1],
                    symbols[1][1],
                    symbols[0][1],
                }, new[] { 0, 2, 0, 1, 1, 1 }.Select(x => (x - baseRotation + 4) % 4).ToArray());
            }
            else
            {
                cube = new Cube(new[] {
                    colors[2][0],
                    colors[4][0],
                    colors[3][0],
                    colors[0][1],
                    colors[1][1],
                    colors[2][1],
                }, new[] {
                    symbols[2][0],
                    symbols[4][0],
                    symbols[3][0],
                    symbols[0][1],
                    symbols[1][1],
                    symbols[2][1],
                }, new[] { 0, 2, 0, 3, 3, 3 }.Select(x => (x - baseRotation + 4) % 4).ToArray());
            }

            break;

        case 1:
            if (!flipped)
            {
                cube = new Cube(new[] {
                    colors[1][1],
                    colors[3][1],
                    colors[2][1],
                    colors[1][2],
                    colors[0][0],
                    colors[1][0],
                }, new[] {
                    symbols[1][1],
                    symbols[3][1],
                    symbols[2][1],
                    symbols[1][2],
                    symbols[0][0],
                    symbols[1][0],
                }, new[] { 0, 2, 0, 1, 3, 3 }.Select(x => (x - baseRotation + 4) % 4).ToArray());
            }
            else
            {
                cube = new Cube(new[] {
                    colors[1][1],
                    colors[3][1],
                    colors[2][1],
                    colors[1][0],
                    colors[0][0],
                    colors[1][2],
                }, new[] {
                    symbols[1][1],
                    symbols[3][1],
                    symbols[2][1],
                    symbols[1][0],
                    symbols[0][0],
                    symbols[1][2],
                }, new[] { 0, 2, 0, 1, 1, 3 }.Select(x => (x - baseRotation + 4) % 4).ToArray());
            }

            break;

        case 2:
            if (!flipped)
            {
                cube = new Cube(new[] {
                    colors[1][1],
                    colors[3][1],
                    colors[2][1],
                    colors[2][2],
                    colors[0][0],
                    colors[1][0],
                }, new[] {
                    symbols[1][1],
                    symbols[3][1],
                    symbols[2][1],
                    symbols[2][2],
                    symbols[0][0],
                    symbols[1][0],
                }, new[] { 0, 2, 0, 0, 3, 3 }.Select(x => (x - baseRotation + 4) % 4).ToArray());
            }
            else
            {
                cube = new Cube(new[] {
                    colors[1][1],
                    colors[3][1],
                    colors[2][1],
                    colors[1][0],
                    colors[0][0],
                    colors[2][2],
                }, new[] {
                    symbols[1][1],
                    symbols[3][1],
                    symbols[2][1],
                    symbols[1][0],
                    symbols[0][0],
                    symbols[2][2],
                }, new[] { 0, 2, 0, 1, 1, 0 }.Select(x => (x - baseRotation + 4) % 4).ToArray());
            }

            break;

        default:
            throw new ArgumentException();
        }

        return(cube);
    }
Beispiel #48
0
 protected virtual void OnShot(Cube owner)
 {
 }
Beispiel #49
0
    static unsafe void RenderThread(Sample sample)
    {
        // initialize the renderer
        Bgfx.Init();
        Bgfx.Reset(sample.WindowWidth, sample.WindowHeight, ResetFlags.Vsync);

        // enable debug text
        Bgfx.SetDebugFeatures(DebugFeatures.DisplayText);

        // set view 0 clear state
        Bgfx.SetViewClear(0, ClearTargets.Color | ClearTargets.Depth, 0x303030ff);

        // create vertex and index buffers
        var vbh = Cube.CreateVertexBuffer();
        var ibh = Cube.CreateIndexBuffer();

        // load shaders
        var program = ResourceLoader.LoadProgram("vs_cubes", "fs_cubes");

        // start the frame clock
        var clock = new Clock();

        clock.Start();

        var imguiController = new ImGuiController(1);

        var image = imguiController.AddTexture(ResourceLoader.LoadTexture("fieldstone-rgba.dds"));

        // main loop
        while (sample.ProcessEvents(ResetFlags.Vsync))
        {
            // set view 0 viewport
            Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight);

            // view transforms
            var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -35.0f), Vector3.Zero, Vector3.UnitY);
            var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 3, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 100.0f);
            Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11);

            // make sure view 0 is cleared if no other draw calls are submitted
            Bgfx.Touch(0);

            // tick the clock
            var elapsed = clock.Frame();
            var time    = clock.TotalTime();

            // write some debug text
            Bgfx.DebugTextClear();
            Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/ImGui");
            Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: Rendering simple static mesh.");
            Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000);

            // submit 11x11 cubes
            for (int y = 0; y < 11; y++)
            {
                for (int x = 0; x < 11; x++)
                {
                    // model matrix
                    var transform = Matrix4x4.CreateFromYawPitchRoll(time + x * 0.21f, time + y * 0.37f, 0.0f);
                    transform.M41 = -15.0f + x * 3.0f;
                    transform.M42 = -15.0f + y * 3.0f;
                    transform.M43 = 0.0f;
                    Bgfx.SetTransform(&transform.M11);

                    // set pipeline states
                    Bgfx.SetVertexBuffer(0, vbh);
                    Bgfx.SetIndexBuffer(ibh);
                    Bgfx.SetRenderState(RenderState.Default);

                    // submit primitives
                    Bgfx.Submit(0, program);
                }
            }

            imguiController.StartFrame();

            ImGui.ShowDemoWindow();

            ImGui.SetNextWindowPos(new Vector2(100, 100));
            ImGui.SetNextWindowSize(new Vector2(400, 400));
            ImGui.Begin("Drawing an image");
            ImGui.Image(image, new Vector2(((float)Math.Sin(clock.TotalTime()) + 1) * 200, ((float)Math.Sin(clock.TotalTime()) + 1) * 200));
            ImGui.End();

            imguiController.EndFrame(elapsed, new Vector2(sample.WindowWidth, sample.WindowHeight));


            // advance to the next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            Bgfx.Frame();
        }

        // clean up
        ibh.Dispose();
        vbh.Dispose();
        program.Dispose();
        Bgfx.Shutdown();
    }
        public override void Do(IDemoChartControl chartControl)
        {
            // Demo volumetric binary data from resources.
            byte[] data = Properties.Resources.skull;

            // Size of data is the same in all 3 dimensions.
            var size = (int)Math.Round(Math.Pow(data.Length, 1d / 3d));

            // Byte, Short, Float types are supported.
            var reader = new ByteIntensityImage3DReader(data, size, size, new OneAxisBounds(data.Min(), data.Max()));

            // This function is used for volume section geometry creation.
            // We just create rectangular geometry moving it along Z axis.
            VolumeGeometry GetGeometry(float relativePosition)
            {
                // Generates surface positions.
                Vector3F[] positions =
                {
                    new Vector3F(0.0f, 0.0f, relativePosition),
                    new Vector3F(1f,   0.0f, relativePosition),
                    new Vector3F(0.0f,   1f, relativePosition),
                    new Vector3F(1f,     1f, relativePosition),
                };
                int[] indices = { 0, 1, 2, 2, 3, 1 };
                return(new CustomVolumeGeometry(new VolumeMesh(positions, positions, indices)));
            }

            VolumeSection GetSection(float relativePosition, float opacity, string name)
            {
                // Create volume section render data.
                return(new VolumeSection
                {
                    // Set section data reader.
                    Reader = reader,
                    // Set section geometry.
                    Geometry = GetGeometry(relativePosition),
                    // Set section interpolation type.
                    InterpolationType = VolumeInterpolationType.Linear,
                    // Set opacity,
                    Opacity = opacity,
                    // Set name.
                    Name = name
                });
            }

            // Bounding box.
            var cube = new Cube
            {
                Size             = new Vector3F(1f),
                Position         = new Vector3F(0.5f),
                Color            = Colors.Black,
                PresentationType = PrimitivePresentationType.Wireframe,
                Name             = "Bounds"
            };

            // Enable 3D axis.
            chartControl.Axes.IsAxes3DVisible = true;

            // Submit render data-s.
            List <RenderData> renderDatas = new List <RenderData>();
            float             sliceStep   = 1.0f / (SliceCount + 1);

            for (int i = 0; i < SliceCount; i++)
            {
                float currentPosition = sliceStep * (i + 1);
                renderDatas.Add(GetSection(currentPosition, 1.0f - currentPosition, $"Section {i}"));
            }
            renderDatas.Add(cube);

            // Set chart data source.
            chartControl.DataSource = renderDatas;
        }
Beispiel #51
0
 public void SetCube(int x, int y, Cube cube)
 {
     cubes[x + y * WIDTH] = cube;
 }
Beispiel #52
0
        public List <M2MMatrixCompressionStat> BuildQueries(Cube cube)
        {
            List <M2MMatrixCompressionStat> listStats = new List <M2MMatrixCompressionStat>();

            foreach (MeasureGroup mg in cube.MeasureGroups)
            {
                if (mg.IsLinked)
                {
                    continue;
                }
                Dictionary <MeasureGroup, List <ManyToManyMeasureGroupDimension> > dictM2M = new Dictionary <MeasureGroup, List <ManyToManyMeasureGroupDimension> >();
                foreach (MeasureGroupDimension mgd in mg.Dimensions)
                {
                    if (mgd is ManyToManyMeasureGroupDimension)
                    {
                        ManyToManyMeasureGroupDimension m2mmgd = (ManyToManyMeasureGroupDimension)mgd;
                        if (!dictM2M.ContainsKey(m2mmgd.MeasureGroup))
                        {
                            dictM2M.Add(m2mmgd.MeasureGroup, new List <ManyToManyMeasureGroupDimension>());
                        }
                        dictM2M[m2mmgd.MeasureGroup].Add(m2mmgd);
                    }
                }
                if (dictM2M.Count > 0)
                {
                    //there are m2m dimensions used by this data measure group
                    foreach (MeasureGroup intermediateMG in dictM2M.Keys)
                    {
                        if (intermediateMG.IsLinked)
                        {
                            continue;
                        }
                        try
                        {
                            List <CubeAttribute> commonDimensions = new List <CubeAttribute>();
                            foreach (CubeDimension cd in cube.Dimensions)
                            {
                                if (mg.Dimensions.Contains(cd.ID) && intermediateMG.Dimensions.Contains(cd.ID))
                                {
                                    if (mg.Dimensions[cd.ID] is RegularMeasureGroupDimension &&
                                        intermediateMG.Dimensions[cd.ID] is RegularMeasureGroupDimension)
                                    {
                                        //it's a common dimension
                                        RegularMeasureGroupDimension rmgdData         = (RegularMeasureGroupDimension)mg.Dimensions[cd.ID];
                                        MeasureGroupAttribute        mgaData          = GetGranularityAttribute(rmgdData);
                                        RegularMeasureGroupDimension rmgdIntermediate = (RegularMeasureGroupDimension)intermediateMG.Dimensions[cd.ID];
                                        MeasureGroupAttribute        mgaIntermediate  = GetGranularityAttribute(rmgdIntermediate);
                                        CubeAttribute ca = mgaData.CubeAttribute;
                                        if (mgaData.AttributeID != mgaIntermediate.AttributeID)
                                        {
                                            if (IsParentOf(mgaIntermediate.Attribute, mgaData.Attribute))
                                            {
                                                ca = mgaIntermediate.CubeAttribute;
                                            }
                                        }
                                        commonDimensions.Add(ca);
                                    }
                                }
                            }

                            //fine while we're just doing this for SQL server
                            MeasureGroupHealthCheckPlugin.sq = "[";
                            MeasureGroupHealthCheckPlugin.fq = "]";

                            DsvTableBinding oTblBinding = new DsvTableBinding(intermediateMG.Parent.DataSourceView.ID, MeasureGroupHealthCheckPlugin.GetTableIdForDataItem(intermediateMG.Measures[0].Source));
                            string          sFactQuery  = "(" + MeasureGroupHealthCheckPlugin.GetQueryDefinition(intermediateMG.ParentDatabase, intermediateMG, oTblBinding, null) + ")";

                            List <string> listCommonDimensionsSeen = new List <string>();
                            string        sCommonDimensions        = "";
                            string        sCommonDimensionsJoin    = "";
                            foreach (CubeAttribute ca in commonDimensions)
                            {
                                RegularMeasureGroupDimension rmgd = (RegularMeasureGroupDimension)intermediateMG.Dimensions[ca.Parent.ID];
                                if (rmgd is ReferenceMeasureGroupDimension)
                                {
                                    if (mg.Dimensions.Contains(((ReferenceMeasureGroupDimension)rmgd).IntermediateCubeDimensionID) &&
                                        mg.Dimensions[((ReferenceMeasureGroupDimension)rmgd).IntermediateCubeDimensionID] is RegularMeasureGroupDimension)
                                    {
                                        continue; //skip reference dimensions in the intermediate measure group because it won't change the cardinality
                                    }
                                    else
                                    {
                                        throw new Exception(rmgd.CubeDimension.Name + " dimension in intermediate measure group " + intermediateMG.Name + " is not supported by BIDS Helper M2M Matrix Compression");
                                    }
                                }

                                MeasureGroupAttribute mga = rmgd.Attributes[ca.AttributeID];
                                foreach (DataItem di in mga.KeyColumns)
                                {
                                    if (di.Source is ColumnBinding)
                                    {
                                        if (!listCommonDimensionsSeen.Contains("[" + ((ColumnBinding)di.Source).ColumnID + "]")) //if this column is already mentioned, then don't mention it again
                                        {
                                            listCommonDimensionsSeen.Add("[" + ((ColumnBinding)di.Source).ColumnID + "]");
                                            if (sCommonDimensionsJoin.Length == 0)
                                            {
                                                sCommonDimensionsJoin += "WHERE ";
                                            }
                                            else
                                            {
                                                sCommonDimensionsJoin += "\r\nAND ";
                                                sCommonDimensions     += ", ";
                                            }
                                            sCommonDimensionsJoin += "f.[" + ((ColumnBinding)di.Source).ColumnID + "] = s.[" + ((ColumnBinding)di.Source).ColumnID + "]";
                                            sCommonDimensions     += "[" + ((ColumnBinding)di.Source).ColumnID + "]";
                                        }
                                    }
                                }
                            }

                            List <string> listM2MDimensionsSeen = new List <string>();
                            string        sM2MDimensions        = "";
                            string        sM2MDimensionsOrderBy = "";
                            foreach (ManyToManyMeasureGroupDimension m2mmgd in dictM2M[intermediateMG])
                            {
                                if (intermediateMG.Dimensions[m2mmgd.CubeDimensionID] is RegularMeasureGroupDimension)
                                {
                                    RegularMeasureGroupDimension rmgd = (RegularMeasureGroupDimension)intermediateMG.Dimensions[m2mmgd.CubeDimensionID];
                                    if (rmgd is ReferenceMeasureGroupDimension)
                                    {
                                        continue;                                         //won't change
                                    }
                                    if (rmgd is ReferenceMeasureGroupDimension)
                                    {
                                        if (mg.Dimensions.Contains(((ReferenceMeasureGroupDimension)rmgd).IntermediateCubeDimensionID) &&
                                            mg.Dimensions[((ReferenceMeasureGroupDimension)rmgd).IntermediateCubeDimensionID] is ManyToManyMeasureGroupDimension)
                                        {
                                            continue; //skip reference dimensions in the intermediate measure group because it won't change the cardinality
                                        }
                                        else
                                        {
                                            throw new Exception(rmgd.CubeDimension.Name + " dimension in intermediate measure group " + intermediateMG.Name + " is not supported by BIDS Helper M2M Matrix Compression");
                                        }
                                    }

                                    MeasureGroupAttribute mga = GetGranularityAttribute(rmgd);
                                    foreach (DataItem di in mga.KeyColumns)
                                    {
                                        if (di.Source is ColumnBinding)
                                        {
                                            if (!listM2MDimensionsSeen.Contains("[" + ((ColumnBinding)di.Source).ColumnID + "]")) //if this column is already mentioned, then don't mention it again
                                            {
                                                listM2MDimensionsSeen.Add("[" + ((ColumnBinding)di.Source).ColumnID + "]");
                                                if (sM2MDimensions.Length > 0)
                                                {
                                                    sM2MDimensions        += " + '|' + ";
                                                    sM2MDimensionsOrderBy += ", ";
                                                }
                                                sM2MDimensions        += "isnull(cast([" + ((ColumnBinding)di.Source).ColumnID + "] as nvarchar(max)),'')";
                                                sM2MDimensionsOrderBy += "[" + ((ColumnBinding)di.Source).ColumnID + "]";
                                            }
                                        }
                                    }
                                }
                            }

                            string sSQL = @"
SELECT (SELECT COUNT(*) FROM " + sFactQuery + @" x) OriginalRecordCount
, COUNT(MatrixKey) MatrixDimensionRecordCount
, SUM(cast(KeyCount AS FLOAT)) CompressedRecordCount
FROM (
 SELECT DISTINCT COUNT(*) KeyCount
 , MatrixKey = (
  SELECT " + sM2MDimensions + @" AS [data()] 
  FROM " + sFactQuery + @" f
  " + sCommonDimensionsJoin + @"
  ORDER BY " + sM2MDimensionsOrderBy + @"
  FOR XML PATH ('')
 )
 FROM " + sFactQuery + @" s 
 GROUP BY " + sCommonDimensions + @"
) SUBQ
";
                            M2MMatrixCompressionStat stat = new M2MMatrixCompressionStat();
                            stat.IntermediateMeasureGroup = intermediateMG;
                            stat.DataMeasureGroup         = mg;
                            stat.SQL = sSQL;
                            listStats.Add(stat);
                        }
                        catch (Exception ex)
                        {
                            M2MMatrixCompressionStat stat = new M2MMatrixCompressionStat();
                            stat.IntermediateMeasureGroup = intermediateMG;
                            stat.DataMeasureGroup         = mg;
                            stat.Error = ex.Message + "\r\n" + ex.StackTrace;
                            listStats.Add(stat);
                        }
                    }
                }
            }

            return(listStats);
        }
Beispiel #53
0
 protected virtual void OnMove(Cube owner, Vector3 target)
 {
 }
Beispiel #54
0
 public abstract void freak(Cylinder set, Sphere setS, Cube setC);
Beispiel #55
0
        /// <summary>
        /// Starts this server asynchronously.
        /// </summary>
        public async Task StartServerAsync()
        {
            this.StartTime = DateTimeOffset.Now;

            this.Logger.LogInformation($"Launching Obsidian Server v{Version} with ID {Id}");
            var stopwatch = Stopwatch.StartNew();

            // Check if MPDM and OM are enabled, if so, we can't handle connections
            if (this.Config.MulitplayerDebugMode && this.Config.OnlineMode)
            {
                this.Logger.LogError("Incompatible Config: Multiplayer debug mode can't be enabled at the same time as online mode since usernames will be overwritten");
                this.StopServer();
                return;
            }

            await Task.WhenAll(Registry.RegisterBlocksAsync(),
                               Registry.RegisterItemsAsync(),
                               Registry.RegisterBiomesAsync(),
                               Registry.RegisterDimensionsAsync(),
                               Registry.RegisterTagsAsync(),
                               Registry.RegisterRecipesAsync());

            Block.Initialize();
            Cube.Initialize();
            ServerImplementationRegistry.RegisterServerImplementations();

            this.Logger.LogInformation($"Loading properties...");
            await(this.Operators as OperatorList).InitializeAsync();
            await this.RegisterDefaultAsync();

            this.Logger.LogInformation("Loading plugins...");
            Directory.CreateDirectory(Path.Join(ServerFolderPath, "plugins")); // Creates if doesn't exist.
            this.PluginManager.DirectoryWatcher.Filters = new[] { ".cs", ".dll" };
            this.PluginManager.DefaultPermissions       = API.Plugins.PluginPermissions.All;
            this.PluginManager.DirectoryWatcher.Watch(Path.Join(ServerFolderPath, "plugins"));
            await Task.WhenAll(Config.DownloadPlugins.Select(path => PluginManager.LoadPluginAsync(path)));

            this.World = new World("world1", this);
            if (!this.World.Load())
            {
                if (!this.WorldGenerators.TryGetValue(this.Config.Generator, out WorldGenerator value))
                {
                    this.Logger.LogWarning($"Unknown generator type {this.Config.Generator}");
                }
                var gen = value ?? new SuperflatGenerator();
                this.Logger.LogInformation($"Creating new {gen.Id} ({gen}) world...");
                this.World.Init(gen);
                this.World.Save();
            }

            if (!this.Config.OnlineMode)
            {
                this.Logger.LogInformation($"Starting in offline mode...");
            }

            Registry.RegisterCommands(this);

            _ = Task.Run(this.ServerLoop);

            this.Logger.LogInformation($"Listening for new clients...");

            stopwatch.Stop();
            Logger.LogInformation($"Server-{Id} loaded in {stopwatch.Elapsed}");

            this.tcpListener.Start();

            while (!this.cts.IsCancellationRequested)
            {
                var tcp = await this.tcpListener.AcceptTcpClientAsync();

                this.Logger.LogDebug($"New connection from client with IP {tcp.Client.RemoteEndPoint}");

                var client = new Client(tcp, this.Config, Math.Max(0, this.clients.Count + this.World.TotalLoadedEntities()), this);
                this.clients.Add(client);
                client.Disconnected += client => clients.TryRemove(client);

                _ = Task.Run(client.StartConnectionAsync);
            }

            this.Logger.LogWarning("Server is shutting down...");
        }
Beispiel #56
0
 public Cube(Cube cube)
     : this()
 {
     Array.Copy(cube.edges, this.edges, EDGE_COUNT);
 }
Beispiel #57
0
        public void DeployScript(ProjectItem projItem, DTE2 ApplicationObject)
        {
            Microsoft.AnalysisServices.Cube oCube = (Microsoft.AnalysisServices.Cube)projItem.Object;
            try
            {
                //validate the script because deploying an invalid script makes cube unusable
                Microsoft.AnalysisServices.Design.Scripts script = new Microsoft.AnalysisServices.Design.Scripts(oCube);
            }
            catch (Microsoft.AnalysisServices.Design.ScriptParsingFailed ex)
            {
                string throwaway = ex.Message;
                MessageBox.Show("MDX Script in " + oCube.Name + " is not valid.", "Problem Deploying MDX Script");
                return;
            }

            if (oCube.MdxScripts.Count == 0)
            {
                MessageBox.Show("There is no MDX script defined in this cube yet.");
                return;
            }

            try
            {
                StatusBar.Animate(true, VsStatusBarAnimations.SBAI_Build);
                StatusBar.Progress(true, "Deploy MDX Script", 1, 5);

                // Check if the file is read-only (and probably checked in to a source control system)
                // before attempting to save. (issue: 10327 )
                FileAttributes fa = System.IO.File.GetAttributes(projItem.get_FileNames(1));
                if ((fa & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                {
                    //TODO - can I check and maybe prompt before saving?
                    //Save the cube
                    projItem.Save("");
                }
                StatusBar.Progress(true, "Deploy MDX Script", 2, 5);

                // extract deployment information
                DeploymentSettings deploySet = new DeploymentSettings(projItem);

                // use xlst to create xmla alter command
                XslCompiledTransform xslt = new XslCompiledTransform();
                XmlReader            xsltRdr;
                XmlReader            xrdr;
                //uint pdwCookie;

                // read xslt from embedded resource
                xsltRdr = XmlReader.Create(new StringReader(BIDSHelper.Resources.Common.DeployMdxScript));
                using ((xsltRdr))
                {
                    // read content from .cube file
                    xrdr = XmlReader.Create(projItem.get_FileNames(1));
                    using (xrdr)
                    {
                        StatusBar.Progress(true, "Deploy MDX Script", 3, 5);
                        // Connect to Analysis Services
                        Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
                        svr.Connect(deploySet.TargetServer);
                        StatusBar.Progress(true, "Deploy MDX Script", 4, 5);
                        // execute the xmla
                        try
                        {
                            Microsoft.AnalysisServices.Scripter scr = new Microsoft.AnalysisServices.Scripter();

                            // Build up the Alter MdxScript command using XSLT against the .cube file
                            XslCompiledTransform xslta = new XslCompiledTransform();
                            StringBuilder        sb    = new StringBuilder();
                            XmlWriterSettings    xws   = new XmlWriterSettings();
                            xws.OmitXmlDeclaration = true;
                            xws.ConformanceLevel   = ConformanceLevel.Fragment;
                            XmlWriter xwrtr = XmlWriter.Create(sb, xws);

                            xslta.Load(xsltRdr);
                            XsltArgumentList xslarg = new XsltArgumentList();

                            Database targetDB = svr.Databases.FindByName(deploySet.TargetDatabase);
                            if (targetDB == null)
                            {
                                throw new System.Exception(string.Format("A database called {0} could not be found on the {1} server", deploySet.TargetDatabase, deploySet.TargetServer));
                            }
                            string targetDatabaseID = targetDB.ID;
                            xslarg.AddParam("TargetDatabase", "", targetDatabaseID);
                            xslta.Transform(xrdr, xslarg, xwrtr);

                            // Extract the current script from the server and keep a temporary backup copy of it
                            StringBuilder     sbBackup = new StringBuilder();
                            XmlWriterSettings xwSet    = new XmlWriterSettings();
                            xwSet.ConformanceLevel   = ConformanceLevel.Fragment;
                            xwSet.OmitXmlDeclaration = true;
                            xwSet.Indent             = true;
                            XmlWriter xwScript = XmlWriter.Create(sbBackup, xwSet);

                            Cube oServerCube = targetDB.Cubes.Find(oCube.ID);
                            if (oServerCube == null)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not yet deployed to the {1} server.", oCube.Name, deploySet.TargetServer));
                            }
                            else if (oServerCube.State == AnalysisState.Unprocessed)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not processed the {1} server.", oCube.Name, deploySet.TargetServer));
                            }
                            if (oServerCube.MdxScripts.Count == 0)
                            {
                                scr.ScriptAlter(new Microsoft.AnalysisServices.MajorObject[] { oServerCube }, xwScript, true);
                            }
                            else
                            {
                                MdxScript mdxScr = oServerCube.MdxScripts[0];
                                scr.ScriptAlter(new Microsoft.AnalysisServices.MajorObject[] { mdxScr }, xwScript, true);
                            }
                            xwScript.Close();

                            // update the MDX Script
                            XmlaResultCollection xmlaRC = svr.Execute(sb.ToString());
                            if (xmlaRC.Count == 1 && xmlaRC[0].Messages.Count == 0)
                            {
                                // all OK - 1 result - no messages
                            }
                            else
                            {
                                StringBuilder sbErr = new StringBuilder();
                                for (int iRC = 0; iRC < xmlaRC.Count; iRC++)
                                {
                                    for (int iMsg = 0; iMsg < xmlaRC[iRC].Messages.Count; iMsg++)
                                    {
                                        sbErr.AppendLine(xmlaRC[iRC].Messages[iMsg].Description);
                                    }
                                }
                                MessageBox.Show(sbErr.ToString(), "BIDSHelper - Deploy MDX Script");
                            }


                            // Test the MDX Script
                            AdomdConnection cn = new AdomdConnection("Data Source=" + deploySet.TargetServer + ";Initial Catalog=" + deploySet.TargetDatabase);
                            cn.Open();
                            AdomdCommand cmd = cn.CreateCommand();
                            string       qry = "SELECT {} ON 0 FROM [" + oCube.Name + "];";
                            cmd.CommandText = qry;
                            try
                            {
                                // test that we can query the cube without errors
                                cmd.Execute();

                                // Building the project means that the .asdatabase file gets re-built so that
                                // we do not break the Deployment Wizard.
                                // --
                                // This line is included in this try block so that it is only executed if we can
                                // successfully query the cube without errors.
                                projItem.DTE.Solution.SolutionBuild.BuildProject(projItem.DTE.Solution.SolutionBuild.ActiveConfiguration.Name, projItem.ContainingProject.UniqueName, false);
                            }
                            catch (System.Exception ex)
                            {
                                // undo the deployment if we caught an exception during the deployment
                                svr.Execute(sbBackup.ToString());
                                MessageBox.Show(ex.Message);
                            }
                            finally
                            {
                                cmd.Dispose();
                                cn.Close();
                            }
                        }
                        catch (System.Exception ex)
                        {
                            if (MessageBox.Show("The following error occured while trying to deploy the MDX Script\r\n"
                                                + ex.Message
                                                + "\r\n\r\nDo you want to see a stack trace?"
                                                , "BIDSHelper - Deploy MDX Script"
                                                , MessageBoxButtons.YesNo
                                                , MessageBoxIcon.Error
                                                , MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                            {
                                MessageBox.Show(ex.StackTrace);
                            }
                        }
                        finally
                        {
                            StatusBar.Progress(true, "Deploy MDX Script", 5, 5);
                            // report any results back (status bar?)
                            svr.Disconnect();
                            svr.Dispose();
                        }
                    }
                }
            }
            finally
            {
                StatusBar.Animate(false, VsStatusBarAnimations.SBAI_Build);
                StatusBar.Progress(false, "Deploy MDX Script", 5, 5);
            }
        }
Beispiel #58
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Main entry-point for this application. </summary>
        ///
        /// <remarks>   Kemp, 1/18/2019. </remarks>
        ///
        /// <param name="args"> An array of command-line argument strings. </param>
        ///-------------------------------------------------------------------------------------------------

        static void Main(string[] args)
        {
            World w = new World();
            Group g = new Group();

            w.AddLight(new LightPoint(new Point(10, 15, -20), new Color(1, 1, 1)));

            /*RTCube room = new RTCube();
             * room.Transform = (Matrix)(RTMatrixOps.Translation(15, 15, -15) * RTMatrixOps.Scaling(15, 15, 15));
             * room.Material.Pattern = new Checked3DPattern(new Color(1,1,1),new Color(.5, .5, .5));
             * room.Material.Pattern.Transform = RTMatrixOps.Scaling(0.05, 0.05, 0.05);
             * room.Material.Ambient = .5;
             * g.AddObject(room);
             */
            /*RTSphere originBall = new RTSphere();
             * originBall.Material.Color = new Color(1, 0, 0);
             * g.AddObject(originBall);
             */
            Cube box1 = new Cube();

            box1.Material.Color   = new Color(1, 1, 1);
            box1.Material.Ambient = new Color(0.3, 0.3, 0.3);
            //box1.Transform = (Matrix)(RTMatrixOps.Translation(9, 1, 4) * RTMatrixOps.RotationY(Math.PI / 4));
            g.AddObject(box1);
            Group gbbc = BoundingBox.Generate(box1);

            g.AddObject(gbbc);

            /*
             * RTCylinder cyl1 = new RTCylinder();
             * // cyl1.Closed = true;
             * cyl1.MaxY = 5;
             * cyl1.MinY = 1;
             * cyl1.Transform = (Matrix)(RTMatrixOps.Scaling(2, 1, 2) * RTMatrixOps.Translation(2, 0, 5));
             * //cyl1.Material.Reflective = 1;
             * cyl1.Material.Color = new Color(0, 0, 1);
             * g.AddObject(cyl1);
             *
             * RTCone cone = new RTCone();
             * cone.Closed = true;
             * cone.MinY = -2;
             * cone.MaxY = 0;
             * //cone.Closed = true;
             * cone.Transform = RTMatrixOps.Translation(5, 2, 6);
             * cone.Material.Color = new Color(.3, .5, .5);
             * g.AddObject(cone);
             */
            w.AddObject(g);
            LineSegment.LineFatness = (1000 * Ops.EPSILON);

            Group gbb = BoundingBox.Generate(g, new Color(1, 0, 0));
            //w.AddObject(gbb);

            Camera camera = new Camera(800, 800, Math.PI / 3);
            //            camera.Transform = RTMatrixOps.ViewTransform(new RTPoint(8, 5, 8), new RTPoint(0, 0, 0), new RTVector(0, 1, 0));
            int nmin = 0;
            int nmax = 10;

            //Console.Write("Press enter to render ...");
            //Console.Read();

            /*for (int n = nmin; n < nmax; n++) {
             *  double theta = ((double)n * Math.PI) / ((double)nmax * 2);
             *  camera.Transform = RTMatrixOps.ViewTransform(new RTPoint(Math.Sin(theta)* 5, 5, -Math.Cos(theta)*5), new RTPoint(0, 0, 0), new RTVector(0, 1, 0));
             *  //camera.Transform = RTMatrixOps.ViewTransform(new RTPoint(5, 5, -5), new RTPoint(0, 0, 0), new RTVector(0, 1, 0));
             *  Console.WriteLine(n.ToString() + " " + theta.ToString() + " (" + (10*Math.Sin(theta)).ToString() + ", 10, "+ (-Math.Cos(theta)*12).ToString() + ")");
             *  Canvas image = w.Render(camera);
             *
             *  String ppm = image.ToPPM();
             *
             *  System.IO.File.WriteAllText(@"ToPPM" + n.ToString() + ".ppm", ppm);
             * }*/

            for (int n = nmin; n < nmax; n++)
            {
                double theta = ((double)n * Math.PI) / ((double)nmax * 2);
                //camera.Transform = RTMatrixOps.ViewTransform(new RTPoint(Math.Sin(theta) * 5, 5, -Math.Cos(theta) * 5), new RTPoint(0, 0, 0), new RTVector(0, 1, 0));
                box1.Transform = (Matrix)(MatrixOps.CreateRotationYTransform(theta) * MatrixOps.CreateRotationZTransform(theta / 2));
                g.RemoveObject(gbbc);
                gbbc = BoundingBox.Generate(box1, new Color(1, 0, 0));
                g.AddObject(gbbc);

                camera.Transform = MatrixOps.CreateViewTransform(new Point(5, 5, -5), new Point(0, 0, 0), new RayTracerLib.Vector(0, 1, 0));
                Console.WriteLine(n.ToString() + " " + theta.ToString() + " (" + (10 * Math.Sin(theta)).ToString() + ", 10, " + (-Math.Cos(theta) * 12).ToString() + ")");
                Canvas image = w.Render(camera);

                /*{
                 *  String ppm = image.ToPPM();
                 *
                 *  System.IO.File.WriteAllText(@"ToPPMa" + n.ToString() + ".ppm", ppm);
                 * }*/

                image.WritePNG("ToPNG" + n.ToString() + ".png");
            }

            Console.Write("Press Enter to finish ... ");
            Console.Read();
        }
 public void CubeCrackEffect(Cube cube, Vector3 spawnPosition)
 {
     StartCoroutine(CubeCrackEffectCoroutine(cube, spawnPosition));
 }
Beispiel #60
0
 public Command(Cube receiver, Vector3 endPosition)
 {
     this.receiver    = receiver;
     this.endPosition = endPosition;
 }