public YaoGraph(Grid3D grid, ConnectionType connectivity) { data = grid; connectivityType = connectivity; edgeset = getEdgeset(); xdim = data.GetLength(0); ydim = data.GetLength(1); zdim = data.GetLength(2); graph = new YaoNode[data.samples.Length]; sample2Yao = new int[data.samples.Length]; int insertionIdx = 0; for (int x = 0; x < xdim; x++) { for (int y = 0; y < ydim; y++) { for (int z = 0; z < zdim; z++) { if (grid[x, y, z] != -1) { graph[insertionIdx] = new YaoNode(grid[x, y, z], -1, float.MaxValue, int.MaxValue, new Vector3(0, 0, 0), edgeset.Count); sample2Yao[grid[x, y, z]] = insertionIdx; assignNeigbors(graph[insertionIdx], x, y, z); insertionIdx++; } } } } rootNodeId = grid[Mathf.FloorToInt(xdim / 2), 0, Mathf.FloorToInt(zdim / 2)]; }
/// <summary> /// Check if the added block is connected to the main robot path (no fully functional) /// </summary> /// <param name="block">The block to validate</param> /// <param name="grid">The voxelgrid</param> /// <returns>Can the block be added or not</returns> private bool ConnectedPath(Block block, Grid3D grid) { var pathFinding = grid.PFinding; var index = block.BlockVoxels.Where(v => v.Type == VoxelType.Block).Select(v => v.Index); var prevVoxels = index.Select(v => grid.GetVoxelAt(v)); foreach (var vox in block.BlockVoxels.Where(v => v.Type == VoxelType.Block)) { //place the block within the voxelgrid grid.AddVoxel(vox); foreach (var face in grid.GetVoxelAt(vox.Index).Faces.Where(f => f.Climable)) { int test = pathFinding.GetPathCount(pathFinding.CreateGraph(), face); if (test != pathFinding.RidiculousHighNumber) { return(true); } } } //restore the original state of the voxelgrid foreach (var v in prevVoxels) { grid.AddVoxel(v); } return(false); }
private void generateGrid(float width, float height, float depth, int nSamples) { cellSize = -1; Triple size = calculateGridSize(width, height, depth, nSamples, ref cellSize); data = new Grid3D(size, cellSize); }
// relevant? public Grid3D getSubgrid(Vector3 p, int extend) { Triple p_grid = imageToGrid(p); Grid3D subgrid = new Grid3D(new Triple(extend, extend, extend), cellSize); int centerIdx = (extend - 1) / 2 + 1; for (int i = 0; i < extend; i++) { for (int j = 0; j < extend; j++) { for (int k = 0; k < extend; k++) { int x = (int)p_grid.x + i - (extend - 1) / 2; int y = (int)p_grid.y + j - (extend - 1) / 2; int z = (int)p_grid.z + k - (extend - 1) / 2; if (x >= 0 && x < data.GetLength(0) && y >= 0 && y < data.GetLength(1) && z >= 0 && z < data.GetLength(2)) { subgrid[i, j, k] = data[x, y, z]; } else { subgrid[i, j, k] = invalid; } } } } return(subgrid); }
#pragma warning restore 0649 #endregion public override Queue <Vector3Int> Modify(Grid3D grid, Vector3Int index) { Core.Cell root; if ((root = grid.TryGetCellByIndex(ref index)) == null) { return(null); } Queue <Vector3Int> newIndexes = new Queue <Vector3Int>(); List <Core.Cell> neighb = grid.GetNeighboursCell(ref index); foreach (Core.Cell cell in neighb) { newIndexes.Enqueue(cell.GetIndex()); } //Modif Vector3Int upIndex = root.GetIndex() + grid.GetConnexAxes()[1]; if (!grid.HaveCell(ref upIndex)) { int height = Random.Range(Min_Random, Max_Random); GameObject prefab = FuncEditor.GetPrefabFromInstance(root.gameObject); for (int i = 0; i < height; i++) { if (!grid.HaveCell(ref upIndex)) { FuncEditor.InstantiateCell(prefab, grid, upIndex); } upIndex += grid.GetConnexAxes()[1]; } } return(newIndexes); }
public override IGrid GetGrid(IDatabaseInfo db) { switch (GridType) { case GridTypes.Structured: return(Grid3D.Cartesian3DGrid( GenericBlas.Linspace(-2.0, 2.0, 2), GenericBlas.Linspace(-1.0, 1.0, 2), GenericBlas.Linspace(-1.0, 1.0, 2))); //return Grid3D.Cartesian3DGrid( // GenericBlas.Linspace(0.0, 2.0, 2), // GenericBlas.Linspace(-1.0, 1.0, 2), // GenericBlas.Linspace(-1.0, 1.0, 2)); //return Grid3D.Cartesian3DGrid( // GenericBlas.Linspace(0.0, 4.0, 2), // GenericBlas.Linspace(-1.0, 1.0, 3), // GenericBlas.Linspace(-1.0, 1.0, 4)); case GridTypes.Unstructured: throw new NotImplementedException(); default: throw new ArgumentException(); } }
/// <summary> /// Исследование создания одномерных сеток /// </summary> private static void GenerateGridTests() { Grid3D grid = new Grid3D(10m, 1m, 0.5m, 10, 5, 5); Console.WriteLine($"Проверка корректности сетки: {grid.GridValidity()}"); var result = grid.InsertLayerX(10m); result = grid.InsertLayerX(0.3m); result = grid.InsertLayerX(0.2m); result = grid.InsertLayerX(0.1m); result = grid.InsertLayerX(9.0m); result = grid.InsertLayerX(1.5m); result = grid.InsertLayerX(4.3m); result = grid.InsertLayerX(9.7m); result = grid.InsertLayerX(9.75m); result = grid.InsertLayerY(0.5m); result = grid.InsertLayerZ(0.43m); Console.WriteLine($"Проверка корректности сетки после вставки слоёв: {grid.GridValidity()}"); ///////////////////////// XmlSerializer formatter = new XmlSerializer(typeof(Grid3D)); using (FileStream fs = new FileStream("grid1D.xml", FileMode.Create)) { formatter.Serialize(fs, grid); Console.WriteLine("Объект сериализован"); } }
private bool changeColor = false; // toogle for color colisions // BallList constructor public BallList(Transform parent, float inputBoxSize, int numBalls, bool varyRadii, bool changeColor) { gameObj.name = "BallList"; // name the empty game object gameObj.transform.parent = parent; // set as child boxSize = inputBoxSize; // get box size this.changeColor = changeColor; // turn on color collisions AddBalls(numBalls, varyRadii); //AddBall_Test(); // Make spatial grid // Calculate cell size such that the box will contain an integer number of cells, each // at least twice the diameter of a ball, if possible float cellSize; int numCellsInBoxSize = Mathf.FloorToInt(boxSize / (ballRadius * 2 * 2)); // number of cells that in boxsize int numCells = 8 * (numCellsInBoxSize * numCellsInBoxSize * numCellsInBoxSize); // total number of cells in box if (numCellsInBoxSize < 1) // if the size of a cell is larger than boxsize, { cellSize = 2 * boxSize; // make the box one big cell numCells = 1; } else { cellSize = boxSize / numCellsInBoxSize; } List <Vector3> positions = balls.Select(o => o.position).ToList(); // make a list of the ball positions grid = new Grid3D <Ball> (cellSize, numCells); // create the grid grid.Fill(positions, balls, ballRadius); // populate the grid }
void Start() { int ranSeed = System.DateTime.Now.Second; // ranSeed = 29; //暂用 Debug.LogWarning("Random seed:" + ranSeed.ToString()); random = new Random(ranSeed); grid = new Grid3D <CellType>(size, Vector3Int.zero); rooms = new List <Room>(); //add by csd placeGrid = new Grid3D <placeWall>(size, Vector3Int.zero); hallways = new List <HallWay>(); pathLst = new List <pathVector>(); stairsLst = new List <stairVector>(); cubeDebugLst = new List <GameObject>(); hallwayDebugLst = new List <GameObject>(); stairDebugLst = new List <GameObject>(); lineDebugLst = new List <GameObject>(); monsterID = 0; //add by csd end createScene(); }
private void RaycastFilledCellsHelper(Ray ray, Grid3D <T> brick, List <T> blackList, PriorityQueue <Vector3i, float> out_found, int x, int y, int z, int width, int height, int depth) { float distance; if (!CollisionUtil.IntersectsBounds(ray, x, y, z, x + width, y + height, z + depth, out distance)) { return; } if (width == 1 && height == 1 && depth == 1) // Work for all empty lists { if (!blackList.Contains(brick.GetValue(x, y, z))) { out_found.Enqueue(new Vector3i(x, y, z), BrickConstants.LARGE_FLOAT - distance); } } else { int newWidth = (width + 1) / 2; int newHeight = (height + 1) / 2; int newDepth = (depth + 1) / 2; RaycastFilledCellsHelper(ray, brick, blackList, out_found, x, y, z, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x + newWidth, y, z, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x, y + newHeight, z, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x, y, z + newDepth, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x + newWidth, y + newHeight, z, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x + newWidth, y, z + newDepth, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x, y + newHeight, z + newDepth, newWidth, newHeight, newDepth); RaycastFilledCellsHelper(ray, brick, blackList, out_found, x + newWidth, y + newHeight, z + newDepth, newWidth, newHeight, newDepth); } }
protected override void Preview(string contentName) { groundGrid = new Grid3D(new Size(10)); var modeldata = ContentLoader.Load <ModelData>(contentName); new Model(modeldata, new Vector3D(0, 0, 0)); }
public void AllCellsUsableAndUnique() { var grid = new Grid3D <int>(100, 50, 24, 33); for (var x = 0; x < grid.Width; x++) { for (var y = 0; y < grid.Height; y++) { for (var z = 0; z < grid.Depth; z++) { grid[x, y, z] = x * grid.Height + y * grid.Depth + z; } } } for (var x = 0; x < grid.Width; x++) { for (var y = 0; y < grid.Height; y++) { for (var z = 0; z < grid.Depth; z++) { Assert.AreEqual(x * grid.Height + y * grid.Depth + z, grid[x, y, z], "({0},{1},{2})", x, y, z); } } } }
public void Resize_NewCellsHaveDefaultValue() { var startWidth = 10; var startHeight = 10; var startDepth = 10; var defaultVal = 5; var grid = new Grid3D <int>(startWidth, startHeight, startDepth, defaultVal); grid.Clear(10); grid.Resize(20, 20, 20); for (var x = 0; x < grid.Width; x++) { for (var y = 0; y < grid.Height; y++) { for (var z = 0; z < grid.Depth; z++) { if (x >= startWidth || y >= startHeight || z >= startDepth) { Assert.AreEqual(defaultVal, grid[x, y, z], "({0},{1},{2})", x, y, z); } else { Assert.AreEqual(10, grid[x, y, z], "({0},{1},{2})", x, y, z); } } } } }
public void Resize_CellsStayTheSame() { int startWidth = 10, startHeight = 15, startDepth = 20; var grid = new Grid3D <int>(startWidth, startHeight, startDepth); for (var x = 0; x < grid.Width; x++) { for (var y = 0; y < grid.Height; y++) { for (var z = 0; z < grid.Depth; z++) { grid[x, y, z] = x * startHeight + y * startDepth + z; } } } grid.Resize(20, 20, 25); for (var x = 0; x < startWidth; x++) { for (var y = 0; y < startHeight; y++) { for (var z = 0; z < startDepth; z++) { Assert.AreEqual(x * startHeight + y * startDepth + z, grid[x, y, z], "({0},{1},{2})", x, y, z); } } } }
/// <summary> /// Instantiate or switch the blockvoxels gameobjects to their new state /// </summary> /// <param name="grid">The global grid</param> public void DrawBlock(Grid3D grid) { InstantiateGoParrentBlock(); foreach (var vox in BlockVoxels) { if (!(vox.Index.x < 0 || vox.Index.y < 0 || vox.Index.z < 0 || vox.Index.x >= Controller.Size.x || vox.Index.y >= Controller.Size.y || vox.Index.z >= Controller.Size.z)) { var gridVox = grid.GetVoxelAt(vox.Index); if ((vox.Type == VoxelType.Block || vox.Type == VoxelType.Connection) && gridVox.Type != VoxelType.Block) { if (gridVox.Go == null) { gridVox.Go = GameObject.Instantiate(Controller.GoVoxel, vox.Index, Quaternion.identity, vox.ParentBlock.goBlockParent.transform); gridVox.Go.name = vox.Name; } if (vox.Type == VoxelType.Connection) { GameObject go = gridVox.Go; var rend = go.GetComponentInChildren <Renderer>(); go.transform.SetParent(vox.ParentBlock.goBlockParent.transform); rend.material = Controller.MatConnection; } else if (vox.Type == VoxelType.Block) { GameObject go = gridVox.Go; var rend = go.GetComponentInChildren <Renderer>(); go.transform.SetParent(vox.ParentBlock.goBlockParent.transform); rend.material = Controller.MatBlock; } } } } }
public ChunkCloud(MaterialCollection materialCollection, Transform map) { MaterialCollection = materialCollection; _map = map; _chunks = new Grid3D <Chunk>(); _chunksMeshes = new Grid3D <MeshBuilder>(); }
public static Grid3D Simulate3D(Grid3D inGrid) { var outGrid = new Grid3D(); var((xMin, xMax), (yMin, yMax), (zMin, zMax)) = inGrid.GetDimensions(); for (var x = xMin - 1; x <= xMax + 1; x++) { for (var y = yMin - 1; y <= yMax + 1; y++) { for (var z = zMin - 1; z <= zMax + 1; z++) { var neighborsCount = GetNeighborsCount3D(inGrid, x, y, z); if (inGrid.IsCubeActive(x, y, z)) { if (neighborsCount == 2 || neighborsCount == 3) { outGrid.SetCubeActive(x, y, z); } } else { if (neighborsCount == 3) { outGrid.SetCubeActive(x, y, z); } } } } } return(outGrid); }
/// <summary> /// Gizmo for debuging a cell. /// </summary> /// <param name="index">The index of the cell.</param> /// <param name="grid">The grid it belongs</param> /// <param name="color">Color of the gizmo.</param> /// <param name="offsetSize"> The scale amount add to the grid size cell.</param> public static void DebugCell(Vector3Int index, Grid3D grid, Color color, float offsetSize = 0.01f) { if (grid == null) { return; } Gizmos.color = color; TypeGrid3D typegrid = grid.GetTypeGrid(); switch (typegrid) { case TypeGrid3D.Cube: { Gizmos.DrawWireCube(grid.GetPositionCell(index), Vector3.one * (grid.SizeCell + offsetSize)); } break; case TypeGrid3D.Hexagonal: { Gizmos.DrawMesh(ProceduralMesh.GetHexagonMesh(), grid.GetPositionCell(index), Quaternion.identity, Vector3.one * (grid.SizeCell + offsetSize)); } break; default: throw new ArgumentException("No type implemented " + typegrid.ToString() + " inherit Grid3D"); } }
/// <summary> /// Validation function. Will check if the block has enough connection voxels. Minimum connections are given in the controller gameobject. /// </summary> /// <param name="block">The block to validate</param> /// <param name="grid">The voxel grid</param> /// <returns>Can the block be added or not</returns> private bool CheckMinConnPoints(Block block, Grid3D grid) { IEnumerable <Vector3Int> connPoints = GetConnectionPoints(grid).Select(pt => pt.Index); IEnumerable <Vector3Int> blocks = block.BlockVoxels.Where(vx => vx.Type == VoxelType.Block).Select(pt => pt.Index); return(connPoints.Intersect(blocks).Count() >= Controller.MinCon); }
/// <summary> /// Update the working grid. /// </summary> /// <param name="selectedGrid"></param> private void UpdateGridSelected(Grid3D selectedGrid) { if (selectedGrid != null) { if (FuncEditor.IsGameObjectInstancePrefab(selectedGrid.gameObject)) { if (EditorUtility.DisplayDialog("Modify Existing Grid Prefab", "The grid selected is a prefab and cannot be modified unless you unpack it. " + "\n Do you want to continue ?", "Yes", "No")) { PrefabUtility.UnpackPrefabInstance(selectedGrid.gameObject, PrefabUnpackMode.OutermostRoot, InteractionMode.UserAction); } else { selectedGrid = null; } } } else { _grid = null; } if (selectedGrid != null && selectedGrid != _grid) { _grid = selectedGrid; } }
public void Generate(Grid3D grid) { var pattern = new PatternC(); foreach (var instance in Instances) { var rotation = instance.Pose.rotation.eulerAngles.ToVector3Int(); Debug.Log("imported rotation " + rotation); if (rotation.x == -90) { rotation.x = 270; } if (rotation.y == -90) { rotation.x = 270; } if (rotation.z == -90) { rotation.x = 270; } Debug.Log("adjusted rotation " + rotation); var block = new Block(pattern, instance.Pose.position.ToVector3Int(), rotation, grid); grid.AddBlockToGrid(block); } }
/// <summary> /// Replace a cell with an other cell, and delete the old, component and gameobject. /// </summary> /// <param name="source">The source gameobject, can be a prefab or an existing gameObject.</param> /// <param name="grid">The grid of the old cell.</param> /// <param name="old">The old cell to replace.</param> /// <returns>The cell component of the new gameobject.</returns> public static Cell ReplaceCell(GameObject source, Grid3D grid, Cell old) { Undo.SetCurrentGroupName("Replace Cell"); int group = Undo.GetCurrentGroup(); GameObject prefab = source; if (IsGameObjectInstancePrefab(source)) { prefab = GetPrefabFromInstance(source); } GameObject gameObject = PrefabUtility.InstantiatePrefab(prefab, grid.transform) as GameObject; Vector3Int index = old.GetIndex(); gameObject.transform.position = old.transform.position; gameObject.name = gameObject.name + "_" + index.x + "_" + index.y + "_" + index.z; Cell cell = gameObject.GetComponent <Cell>(); if (cell == null) { gameObject.AddComponent <Cell>(); } grid.ReplaceCell(index, cell); Undo.RegisterCreatedObjectUndo(cell.gameObject, "Cell replaced"); Undo.DestroyObjectImmediate(old.gameObject); Undo.CollapseUndoOperations(group); return(cell); }
protected override void AfterModify(Grid3D grid) { foreach (Vector3Int index in _to_instantiate) { FuncEditor.InstantiateCell(prefab, grid, index); } }
void Start() { grid = FindObjectOfType <Grid3D>(); radius = player.GetAbilityValueInt(Ability.AbilityType.BombExplosionRadius); player.OnBombPlanted(); timerCoroutine = StartCoroutine(StartTimer()); }
/// <summary> /// Refresh a grid. Only work outside playMode. /// </summary> /// <param name="grid"> The grid to refresh.</param> public static void RefreshGrid(Grid3D grid) { if (!Application.isPlaying) { grid.Initialize(); } }
public void Fill_OnlyTouchesCube() { var width = 100; var height = 50; var depth = 24; var grid = new Grid3D <int>(width, height, depth, 33); int minX = 5, minY = 10, minZ = 8; int maxX = width - 5, maxY = height - 10, maxZ = depth - 8; grid.Fill(1, minX, minY, minZ, maxX, maxY, maxZ); for (var x = 0; x < grid.Width; x++) { for (var y = 0; y < grid.Height; y++) { for (var z = 0; z < grid.Depth; z++) { // outside cube if (x < minX || x > maxX || y < minY || y > maxY || z < minZ || z > maxZ) { Assert.AreEqual(33, grid[x, y, z], "({0},{1},{2})", x, y, z); } else { Assert.AreEqual(1, grid[x, y, z], "({0},{1},{2})", x, y, z); } } } } }
protected override void AfterModify(Grid3D grid) { foreach (Cell c in _to_delete) { FuncEditor.DestroyCell(c); } last_index = last_index + Vector3Int.up; }
public static int Part1(Grid3D grid, int cyclesCount) { for (var i = 0; i < cyclesCount; i++) { grid = Simulate3D(grid); } return(grid.ActiveCubesCount); }
public Block GetNextBlock(Grid3D grid) { // The connection points, sorted by distance. IEnumerable <Voxel> byDistance = SortByDistance(GetConnectionPoints(grid)); IEnumerable <Block> blocksFromDistance = byDistance.SelectMany(b => new Block[] { new Block(new PatternA(), b, grid), new Block(new PatternB(), b, grid) }); return(blocksFromDistance.FirstOrDefault(bl => Validate(bl, grid))); }
// Start is called before the first frame update void Awake() { grid = GetComponent <Grid3D>(); colourMenu = GameObject.Find("Radial Menu - Colours").GetComponent <RadialMenu>(); tempObject = null; grid.OnGridInitialised += Grid_OnGridInitialised; }
public void RenderGridWithCenterInOtherPosition() { var grid = new Grid3D(new Vector3D(5, 5, 0), new Size(1)); new Line3D(Vector3D.Zero, Vector3D.UnitX, Color.Red); new Line3D(Vector3D.Zero, Vector3D.UnitY, Color.Green); new Line3D(Vector3D.Zero, Vector3D.UnitZ, Color.Blue); AssertQuadraticGrid(1, grid); new Line3D(new Vector3D(5, 5, 0), new Vector3D(5, 5, 1), Color.Blue); foreach (var line in grid.lines) Assert.IsTrue(line.IsActive); Assert.AreEqual(new Vector3D(5, 5, 0), grid.Position); }
private static void AssertQuadraticGrid(int expectedDimension, Grid3D grid) { Assert.AreEqual(new Size(expectedDimension, expectedDimension), grid.Dimension); }
public void RedrawGridIfItChanges() { var grid = new Grid3D(new Size(1)); Assert.AreEqual(4, EntitiesRunner.Current.GetEntitiesOfType<Line3D>().Count); grid.Dimension = new Size(10); Assert.AreEqual(22, EntitiesRunner.Current.GetEntitiesOfType<Line3D>().Count); }
/// <summary> /// Initializes a new instance of the <see cref="PathNode{T}"/> class.</summary> /// <param name="node"> /// The <see cref="IGraph2D{TNode}"/> node that the <see cref="PathNode{T}"/> represents. /// </param> /// <param name="childrenCount"> /// The initial capacity of the <see cref="Children"/> collection.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="children"/> is less than zero.</exception> /// <remarks> /// The specified <paramref name="children"/> should equal the <see /// cref="IGraph2D{TNode}.Connectivity"/> of the <see cref="IGraph2D{TNode}"/> instance on which the /// path search is performed, so as to avoid costly reallocations.</remarks> public PathNodeCell(Cell node, Grid3D grid, int childrenCount) : base(node, node.Polygon, grid) { _children = new ListEx<PathNodeCell>(childrenCount); }
public static Mesh Construct(Grid3D metaResource) { Mesh[] meshes = new Mesh[metaResource.NDepth]; for (int i = 0; i < metaResource.NDepth; i++) { meshes[i] = Construct(new Grid { MeshType = metaResource.MeshType, NHeight = metaResource.NHeight, NWidth = metaResource.NWidth, Size = new Vector2(metaResource.Size.X, metaResource.Size.Y), Position = metaResource.Position + new Vector3(0, 0, metaResource.Size.Z * i / (float)metaResource.NDepth), UVMin = metaResource.UVMin, UVMax = metaResource.UVMax }); } return Mesh.Combine(meshes); }
// Destroy everything, reset to initial values private void Reset() { tiles = new Grid3D<Tile>(world_width, world_length, world_height); entities = new List<Entity>(); }
public void UpdateCenterOfGrid() { var grid = new Grid3D(new Size(1)); Assert.AreEqual(Vector3D.Zero, grid.Position); grid.Position = new Vector3D(1, 1, 0); Assert.AreEqual(4, EntitiesRunner.Current.GetEntitiesOfType<Line3D>().Count); Assert.AreEqual(new Vector3D(1, 1, 0), grid.Position); }