public static VoxelCommand Add(Voxel voxel) { VoxelCommand cmd = new VoxelCommand (); cmd._type = Type.Add; cmd._voxel = voxel; return cmd; }
public void Add(Voxel voxel) { voxel.position -= this.Position; if (Voxels[(int)voxel.position.X, (int)voxel.position.Y, (int)voxel.position.Z] != null) return; //if (!inChunk(voxel.position)) return; //this.Remove(voxel); Voxels[(int)voxel.position.X, (int)voxel.position.Y, (int)voxel.position.Z] = voxel; if (((int)voxel.position.X + 1 < this.Size.X && Voxels[(int)voxel.position.X + 1, (int)voxel.position.Y, (int)voxel.position.Z] == null) || (int)voxel.position.X == this.Size.X - 1) vertices.AddRange(Face.getFace( Face.Facing.Right, voxel.position, voxel.color)); if (((int)voxel.position.X - 1 >= 0 && Voxels[(int)voxel.position.X - 1, (int)voxel.position.Y, (int)voxel.position.Z] == null) || (int)voxel.position.X == 0) vertices.AddRange(Face.getFace( Face.Facing.Left, voxel.position, voxel.color)); if (((int)voxel.position.Y + 1 < this.Size.Y && Voxels[(int)voxel.position.X, (int)voxel.position.Y + 1, (int)voxel.position.Z] == null) || (int)voxel.position.Y == this.Size.Y - 1) vertices.AddRange(Face.getFace( Face.Facing.Up, voxel.position, voxel.color)); if (((int)voxel.position.Y - 1 >= 0 && Voxels[(int)voxel.position.X, (int)voxel.position.Y - 1, (int)voxel.position.Z] == null) || (int)voxel.position.Y == 0) vertices.AddRange(Face.getFace( Face.Facing.Down, voxel.position, voxel.color)); if (((int)voxel.position.Z + 1 < this.Size.Z && Voxels[(int)voxel.position.X, (int)voxel.position.Y, (int)voxel.position.Z + 1] == null) || (int)voxel.position.Z == this.Size.Z - 1) vertices.AddRange(Face.getFace( Face.Facing.Forward, voxel.position, voxel.color)); if (((int)voxel.position.Z - 1 >= 0 && Voxels[(int)voxel.position.X, (int)voxel.position.Y, (int)voxel.position.Z - 1] == null) || (int)voxel.position.Z == 0) vertices.AddRange(Face.getFace( Face.Facing.Backward, voxel.position, voxel.color)); this.Build(); }
public void RemoveVoxelAnimation(bool hasPreviousBlock, Voxel voxel, Action finishCallback) { if (_animDic.ContainsKey(voxel.Pos)) { AnimTuple anim = _animDic[voxel.Pos]; anim.Trans.GetComponent<MeshRenderer>().material.color = voxel.Color; anim.Trans.GetComponent<DummyBehavior>().StopAllCoroutines(); anim.Cor = anim.Trans.GetComponent<DummyBehavior>().StartCoroutine(RemoveVoxelAnimationCor(voxel.Pos, anim.Trans, () => { finishCallback(); })); } else { if (hasPreviousBlock) { AnimTuple anim = new AnimTuple(); _animDic[voxel.Pos] = anim; anim.Trans = CreateAnimTransform(voxel); anim.Trans.localScale = Vector3.one; anim.Cor = anim.Trans.GetComponent<DummyBehavior>().StartCoroutine(RemoveVoxelAnimationCor(voxel.Pos, anim.Trans, () => { finishCallback(); })); } } }
static Voxel[] GetDataFromString(int width, int height, int depth, string dataString) { string[] layers = dataString.Split ('-'); int size = height * depth * width; Voxel[] data = new Voxel[size]; int c = 0; foreach (string layer in layers) { string[] lines = layer.Split ('\n'); foreach (string line in lines) { string row = line.Trim (); for (int i = 0; i < row.Length; i++) { Voxel v = new Voxel(); int j; if (int.TryParse (row [i] + "", out j)) { v.id = (byte)j; } else { v.id = 0; } // cut in the middle of processing if (c == size) { return data; } data [c++] = v; } } } if (c != size) { throw new Exception ("insuficient voxel data"); } return data; }
public void Initialize(int resolution, float size) { this.m_resolution = resolution; m_gridSize = size; m_voxelSize = size / resolution; m_voxels = new Voxel[resolution * resolution]; m_voxelMaterials = new Material[m_voxels.Length]; for (int i = 0, y = 0; y < resolution; y++) { for (int x = 0; x < resolution; x++, i++) { CreateVoxel(i, x, y); } } m_dummyX = new Voxel(); m_dummyY = new Voxel(); m_dummyT = new Voxel(); //offset the grid to center it inside the screen Vector3 gridPosition = new Vector3(-0.5f * size, -0.5f * size, 0); this.transform.localPosition = gridPosition; GetComponent<MeshFilter>().mesh = m_mesh = new Mesh(); m_mesh.name = "VoxelGrid Mesh"; m_vertices = new List<Vector3>(); m_triangles = new List<int>(); Refresh(); }
public void InstantiateVoxels(int startx, int starty, int startz, int width, int height, int depth) { Width = width; Height = height; Depth = depth; Voxels = new Voxel[Width, Height, Depth]; float voxelSize = VoxelWorld.Inst.PhysicalVoxelSize; float halfVoxel = voxelSize * 0.5f; for (int x = 0; x < Width; ++x) { for (int y = 0; y < Height; ++y) { for (int z = 0; z < Depth; ++z) { IntVec3 pos = new IntVec3(startx + x, starty + y, startz + z); BoxCollider collider = gameObject.AddComponent<BoxCollider>(); collider.center = new Vector3(pos.X + halfVoxel, pos.Y + halfVoxel, pos.Z + halfVoxel); collider.size = new Vector3(voxelSize, voxelSize, voxelSize); Voxel voxel = new Voxel(this, VoxelType.Air, pos, collider); Voxels[x, y, z] = voxel; ColliderToVoxel[collider] = voxel; } } } }
void DetectVoxels () { if (currentVoxel == null) currentVoxel = new Voxel (); }
void detector_Collided(Volume collisonObject, Voxel voxel, Vector3 worldPosition) { // If the bullet hits an invader and is owned by the player, explode and destroy the invader - and deactivate the bullet if (collisonObject.name == "Invader" && Owner is InvadersPlayerShip) { collisonObject.Destruct(3f, true); Destroy(collisonObject.gameObject); gameObject.SetActive(false); } // If we hit a shield, just explode and deactivate the bullet if (collisonObject.name == "Shield") { exploder.ExplosionRadius = 1f; exploder.Explode(); gameObject.SetActive(false); } // If we hit the player ship if (collisonObject.name == "Player Ship") { collisonObject.Destruct(3f, true); collisonObject.GetComponent<InvadersPlayerShip>().Die(); gameObject.SetActive(false); } }
public void AddVoxel(Voxel voxel) { _voxelAnimation.AddVoxelAnimation(_voxelData.HasVoxelAtPos(voxel.Pos), voxel, () => { _voxelData.AddVoxel(voxel); _voxelRenderer.RenderMesh(_voxelData); }); }
private void detector_Collided(Volume collisonObject, Voxel voxel, Vector3 worldPosition) { if (collisonObject.name.StartsWith("Plane") && Owner is ShmupChopper) { collisonObject.GetComponent<ShmupPlane>().Die(); gameObject.SetActive(false); } }
public static Voxel[] GetNeighbours(Point3 worldCoord) { Voxel[] neighbours = new Voxel[6]; for (int i=0; i<checkSides.Length; i++) { neighbours[i] = ChunkManager.GetBlock(worldCoord + checkSides[i]); } return neighbours; }
// TODO: Cache all the binary formatters public static byte[] SeralizeVoxel(Voxel voxel) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, voxel); return stream.ToArray(); } }
public void BecomeYDummyOf (Voxel voxel, float offset) { state = voxel.state; position = voxel.position; xEdgePosition = voxel.xEdgePosition; yEdgePosition = voxel.yEdgePosition; position.y += offset; xEdgePosition.y += offset; yEdgePosition.y += offset; }
public void Set(int x, int y, int z, Voxel voxel) { if (voxels.GetLength(0) < x || voxels.GetLength(1) < y || voxels.GetLength(2) < z) { return; } voxels[x, y, z] = voxel; }
public override Voxel.State Apply(int x, int y, Voxel.State voxel) { x -= centerX; y -= centerY; if (x * x + y * y <= sqrRadius) { return fillType; } return voxel; }
public void SetVoxel (Voxel vox, Vector3 pos){ pos = new Vector3((int)pos.x, (int)pos.y, (int)pos.z); if (grid.ContainsKey (pos)) { // Debug.Log ("voxel " + vox + " overwriting space " + pos + ", previously occupied by " + grid[pos]); grid[pos] = vox; } else{ grid.Add (pos, vox); } }
public void BecomeYDummyOf(Voxel voxel, float offset) { m_state = voxel.m_state; m_position = voxel.m_position; m_xEdgePosition = voxel.m_xEdgePosition; m_yEdgePosition = voxel.m_yEdgePosition; m_position.y += offset; m_xEdgePosition.y += offset; m_yEdgePosition.y += offset; }
// Requires neighbours to be listed in correct order. // Returns the sum of each neighbour's ID. public static int GetID(Voxel[] neighbours) { int id = 0; for (int i=0; i<neighbours.Length; i++) { if (neighbours[i] == null) { continue; } id += neighbourIDs[i]; } return id; }
public void BecomeYDummyOf(Voxel voxel, float offset) { state = voxel.state; position = voxel.position; eastEdge = voxel.eastEdge; southEdge = voxel.southEdge; cornerPosition = voxel.cornerPosition; position.z -= offset; eastEdge.z -= offset; southEdge.z -= offset; cornerPosition.z -= offset; }
// Given new chunk of voxels, reset and rebuild mesh public void UseVoxels(Voxel[] src_voxels, int chunkx, int chunky) { // If this chunk already displays given voxels, do nothing if (this.voxels == src_voxels) { return; } this.chunkX = chunkx; this.chunkY = chunky; this.voxels = src_voxels; RebuildMesh(); }
void ShmupChopper_Collided(Volume collisonObject, Voxel voxel, Vector3 worldPosition) { if (collisonObject.gameObject == gameObject) return; if(!(collisonObject.name.StartsWith("Playfield") || collisonObject.name.StartsWith("Plane"))) return; // Destruct the volume a few times with different velocities to make lots of particles! GetComponent<Volume>().Destruct(0f, false); GetComponent<Volume>().Destruct(5f, false); explodeParticleSystem.transform.position = transform.position; explodeParticleSystem.Emit(30); gameObject.SetActive(false); Invoke("Respawn", 3f); }
static string GetStringFromData(int width, int height, int depth, Voxel[] data) { string dataString = ""; for (int y = 0; y < height; y++) { for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { dataString += data [y * (depth * width) + z * width + x].id; } dataString += "\n"; } dataString += "-\n"; } return dataString; }
public void RemoveVoxel(Vector3Int pos) { if (_voxelData.HasVoxelAtPos(pos)) { Voxel voxel = new Voxel(); voxel = _voxelData.VoxelAtPos(pos); _voxelData.RemoveVoxel(pos); _voxelRenderer.RenderMesh(_voxelData); _voxelAnimation.RemoveVoxelAnimation(true, voxel, () => { // None needed }); } }
private Task oneTask(Voxel vox) { TaskSet task = new TaskSet (); TweenTask tt1 = new TweenTask(delegate { return TweenLocalPosition.Begin(vox.gameObject, Random.Range(0.3f, 0.5f), new Vector3(Random.Range(-100f, 100f),Random.Range(-100f, 100f),Random.Range(-100f, 100f))); }); TaskManager.PushBack (tt1, delegate { vox.gameObject.SetActive(false); }); task.push (tt1); return task; }
/** * Clear the tree and subtrees */ public void Clear() { m_hashKey = int.MinValue; m_voxel = null; m_parentHashTree = null; if(m_leftHashTree != null) { m_leftHashTree.Clear(); m_leftHashTree = null; } if(m_rightHashTree != null) { m_rightHashTree.Clear(); m_rightHashTree = null; } }
void Start() { Voxel v = new Voxel(); // Theme: 5 bits // Block: 5 bits // Variant: 6 bits // Rotation x: 2 bits // Rotation y: 2 bits // Rotation z: 2 bits string theme = "11111"; string block = "11111"; string variant = "111111"; string rotX = "11"; string rotY = "01"; string rotZ = "00"; string data = theme + block + variant + rotX + rotY + rotZ; v.data = Convert.ToInt32(data, 2); Debug.Log("Raw data: "+v.data); Debug.Log("Binary data: "+ v.GetBinaryString()); // Change theme from space to western Debug.Log("Theme: "+v.GetTheme()); Debug.Log("Set theme: Theme.DEFAULT"); v.SetTheme(Theme.DEFAULT); Debug.Log("Binary data: "+v.GetBinaryString()); Debug.Log("Theme: "+v.GetTheme()); Debug.Log("BlockID: "+v.GetBlockType()); Debug.Log("Set block ID: 0"); v.SetBlockType(0); Debug.Log("Binary data: "+v.GetBinaryString()); Debug.Log("BlockID NEW: "+v.GetBlockType()); Debug.Log("Variant before: "+v.GetVariant()); Debug.Log("Set variant: 2"); v.SetVariant(2); Debug.Log("Binary data: "+v.GetBinaryString()); Debug.Log("Variant after: "+v.GetVariant()); Debug.Log("Rotation before: "+v.GetRotation().eulerAngles); Debug.Log("Set rotation: 270, 0, 0"); v.SetRotation(Quaternion.Euler(270f, 0f, 0f)); Debug.Log("Binary data: "+v.GetBinaryString()); Debug.Log("Rotation after: "+v.GetRotation().eulerAngles); }
public void AddVoxelAnimation(bool hasPreviousBlock, Voxel voxel, Action finishCallback, bool firstTime = true) { if (_animDic.ContainsKey(voxel.Pos) && firstTime) // Animation going on at this point { RemoveVoxelAnimation(hasPreviousBlock, voxel, () => { AddVoxelAnimation(false, voxel, () => { finishCallback(); }, false); }); } else if (_animDic.ContainsKey(voxel.Pos)) { AnimTuple anim = _animDic[voxel.Pos]; anim.Trans.GetComponent<MeshRenderer>().material.color = voxel.Color; anim.Cor = anim.Trans.GetComponent<DummyBehavior>().StartCoroutine(AddVoxelAnimationCor(voxel.Pos, anim.Trans, () => { finishCallback(); })); } else // No animation going on at this point { if (hasPreviousBlock) { RemoveVoxelAnimation(hasPreviousBlock, voxel, () => { AddVoxelAnimation(false, voxel, () => { finishCallback(); }, false); }); } else { AnimTuple anim = new AnimTuple(); _animDic[voxel.Pos] = anim; anim.Trans = CreateAnimTransform(voxel); anim.Cor = anim.Trans.GetComponent<DummyBehavior>().StartCoroutine(AddVoxelAnimationCor(voxel.Pos, anim.Trans, () => { finishCallback(); })); } } }
public virtual void SetVoxel(IntVector3 pos, Voxel voxel) { lock (Voxels) { if (voxel != Voxel.Empty) Voxels[pos] = voxel; else Voxels.Remove(pos); } if((pos.X < Start.X || pos.Y < Start.Y || pos.Z < Start.Z) || (pos.X > End.X || pos.Y > End.Y || pos.Z > End.Z)) UpdateBounds(pos, pos); if (Updated != null) Updated(this); }
//an internal intention can be overidden by external of higher priority //an external intention that moves will not override an internal intention that is stationary //two move actions cannot both occur //two still intentions cannot both occur //if heldforstep, it cannot change moveAction; public void SetIntention(Voxel motivator, Vector3 intendedPos, int comPriority, IntentionDelegate intendedFunc, bool involvesMovement){ // Debug.Log ("SetIntention:: held: " + heldInPlace + " self motivated: " + (motivator == this) + " involvesMovement: " + involvesMovement); if (heldInPlace && motivator == this && involvesMovement) { // Debug.Log("Voxel " + this + " is held in place and cannot move itself this step"); return; } if (involvesMovement && comPriority < intentionPriority) { // Debug.Log("Setting move action for " + this); intentionPriority = comPriority; intendedPosition = intendedPos; MoveAction = intendedFunc; } else if (!involvesMovement){ // Debug.Log("Setting still action for " + this); StillAction = intendedFunc; } }
public SilverLiningCumulusCloud (float width, float height, float depth, Vector3 position) { voxelSize *= (float)SilverLining.unitScale; quickLightingAttenuation *= SilverLining.unitScale; sizeX = (int)(width / voxelSize); sizeY = (int)(height / voxelSize); sizeZ = (int)(depth / voxelSize); if (shuriken) { particles = new ParticleSystem.Particle[sizeX * sizeY * sizeZ]; } else { legacyParticles = new Particle[sizeX * sizeY * sizeZ]; } voxels = new Voxel[sizeX * sizeY * sizeZ]; alpha = 1.0f; double dropletsPerCubicM = (dropletsPerCubicCm / Math.Pow (SilverLining.unitScale, 3.0)) * 100 * 100 * 100; dropletSize *= SilverLining.unitScale; opticalDepth = (Math.PI * (dropletSize * dropletSize) * voxelSize * dropletsPerCubicM); cloudPrefab = GameObject.Find (shuriken ? "CumulusCloudPrefab" : "CumulusCloudPrefabLegacy"); if (cloudPrefab != null) { cloudObject = (GameObject)GameObject.Instantiate (cloudPrefab, position, Quaternion.identity); GameObject cloudLayer = GameObject.Find ("CumulusClouds"); if (cloudLayer) { cloudObject.transform.parent = cloudLayer.transform; } if (shuriken) { particleSystem = cloudObject.GetComponent<ParticleSystem> (); particleSystem.renderer.enabled = true; } else { emitter = cloudObject.GetComponent<ParticleEmitter> (); cloudObject.GetComponent<ParticleRenderer> ().enabled = true; } InitializeVoxels (); } }
public Vector3[] getSubMesh(Mesh majorMesh, Vector3[] centerPoints, int i, int shatterLevel, Voxel majorVoxel) { int subsequent = (i + 1) % 3 + (i > 2 ? 3 : 0); Vector3[] verts = new Vector3[6]; float variation = 0.5f; Vector3[] majorVerts = new Vector3[6]; int count = 0; for (int j = 0; j < 6; j++) { int ind; if (majorVoxel.deletedPoints.Contains(i)) { //ind = (j + 3 - majorVoxel.deletedPoints.Count) % (6 - majorVoxel.deletedPoints.Count); ind = (j + 3) % 6; } else { //ind = count; ind = j; count++; } try { majorVerts[j] = majorMesh.vertices[ind]; } catch { Debug.LogError("trying to index vert list of len " + majorMesh.vertices.Length + " with ind = " + ind + " j = " + j + " count = " + count + " num deleted = " + majorVoxel.deletedPoints.Count); } } if (shatterLevel == 0 && !false) { if (i < 6) {//the first 6 are outter(bottom and top) int remaining = findRemainingOnSide(new int[] { i, subsequent })[0]; verts[0] = majorVerts[i]; verts[1] = majorVerts[i] + (majorVerts[subsequent] - majorVerts[i]) * (0.5f - variation / 2.0f + randDev[i % 3] * variation); verts[2] = majorVerts[i] + (majorVerts[remaining] - majorVerts[i]) * (0.5f + variation / 2.0f - randDev[remaining % 3] * variation); verts[3] = getMidPoint(majorVerts, i); verts[4] = getMidPoint(majorVerts, i) + (getMidPoint(majorVerts, subsequent) - getMidPoint(majorVerts, i)) * (0.5f - variation / 2.0f + randDev[i % 3] * variation); verts[5] = getMidPoint(majorVerts, i) + (getMidPoint(majorVerts, remaining) - getMidPoint(majorVerts, i)) * (0.5f + variation / 2.0f - randDev[remaining % 3] * variation); } else {//the inner triangles- one bottom one top int a = (i == 6 ? 0 : 3); for (int k = 0; k < 3; k++) { verts[k] = majorVerts[k + a] + (majorVerts[(k + 1) % 3 + a] - majorVerts[k + a]) * (0.5f - variation / 2.0f + randDev[k % 3] * variation); verts[k + 3] = getMidPoint(majorVerts, k + a) + (getMidPoint(majorVerts, (k + 1) % 3 + a) - getMidPoint(majorVerts, k + a)) * (0.5f - variation / 2.0f + randDev[k % 3] * variation); } } } else { if (i < 3) {//the first 6 are outter(bottom and top) int remaining = findRemainingOnSide(new int[] { i, subsequent })[0]; verts[0] = majorVerts[i]; verts[1] = majorVerts[i] + (majorVerts[subsequent] - majorVerts[i]) * (0.5f - variation / 2.0f + randDev[i % 3] * variation); verts[2] = majorVerts[i] + (majorVerts[remaining] - majorVerts[i]) * (0.5f + variation / 2.0f - randDev[remaining % 3] * variation); verts[3] = majorVerts[i + 3]; verts[4] = majorVerts[i + 3] + (majorVerts[subsequent + 3] - majorVerts[i + 3]) * (0.5f - variation / 2.0f + randDev[i % 3] * variation); verts[5] = majorVerts[i + 3] + (majorVerts[remaining + 3] - majorVerts[i + 3]) * (0.5f + variation / 2.0f - randDev[remaining % 3] * variation); } else {//the inner triangles- one bottom one top for (int k = 0; k < 3; k++) { verts[k] = majorVerts[k + 0] + (majorVerts[(k + 1) % 3 + 0] - majorVerts[k + 0]) * (0.5f - variation / 2.0f + randDev[k % 3] * variation); verts[k + 3] = majorVerts[k + 3] + (majorVerts[(k + 1) % 3 + 3] - majorVerts[k + 3]) * (0.5f - variation / 2.0f + randDev[k % 3] * variation); } } } return(verts); }
/// <summary> /// SETUP MOORES & VON NEUMANN 3D NEIGHBORS /// </summary> void SetupNeighbors3d() { for (int i = 1; i < width - 1; i++) { for (int j = 1; j < length - 1; j++) { for (int k = 1; k < height - 1; k++) { //the current voxel we are looking at... GameObject currentVoxelObj = voxelGrid[i, j, k]; ////SETUP Von Neumann Neighborhood Cells//// Voxel[] tempNeighborsVN = new Voxel[6]; //left Voxel VoxelLeft = voxelGrid[i - 1, j, k].GetComponent <Voxel>(); currentVoxelObj.GetComponent <Voxel>().setVoxelLeft(VoxelLeft); tempNeighborsVN[0] = VoxelLeft; //right Voxel VoxelRight = voxelGrid[i + 1, j, k].GetComponent <Voxel>(); currentVoxelObj.GetComponent <Voxel>().setVoxelRight(VoxelRight); tempNeighborsVN[2] = VoxelRight; //back Voxel VoxelBack = voxelGrid[i, j - 1, k].GetComponent <Voxel>(); currentVoxelObj.GetComponent <Voxel>().setVoxelBack(VoxelBack); tempNeighborsVN[3] = VoxelBack; //front Voxel VoxelFront = voxelGrid[i, j + 1, k].GetComponent <Voxel>(); currentVoxelObj.GetComponent <Voxel>().setVoxelFront(VoxelFront); tempNeighborsVN[1] = VoxelFront; //below Voxel VoxelBelow = voxelGrid[i, j, k - 1].GetComponent <Voxel>(); currentVoxelObj.GetComponent <Voxel>().setVoxelBelow(VoxelBelow); tempNeighborsVN[4] = VoxelBelow; //above Voxel VoxelAbove = voxelGrid[i, j, k + 1].GetComponent <Voxel>(); currentVoxelObj.GetComponent <Voxel>().setVoxelAbove(VoxelAbove); tempNeighborsVN[5] = VoxelAbove; //Set the Von Neumann Neighbors [] in this Voxel currentVoxelObj.GetComponent <Voxel>().setNeighbors3dVN(tempNeighborsVN); ////SETUP Moore's Neighborhood//// Voxel[] tempNeighborsMO = new Voxel[26]; int tempcount = 0; for (int m = -1; m < 2; m++) { for (int n = -1; n < 2; n++) { for (int p = -1; p < 2; p++) { if ((i + m >= 0) && (i + m < width) && (j + n >= 0) && (j + n < length) && (k + p >= 0) && (k + p < height)) { GameObject neighborVoxelObj = voxelGrid[i + m, j + n, k + p]; if (neighborVoxelObj != currentVoxelObj) { Voxel neighborvoxel = voxelGrid[i + m, j + n, k + p].GetComponent <Voxel>(); tempNeighborsMO[tempcount] = neighborvoxel; tempcount++; } } } } } currentVoxelObj.GetComponent <Voxel>().setNeighbors3dMO(tempNeighborsMO); } } } }
void InitVoxelSpace(Point3 size) { transform.localRotation = Quaternion.identity; Orientation = Direction.South; // Clear the old boxes foreach (Transform t in this.transform) { if (t != frameTransform) { Destroy(t.gameObject); } } int length = size.x; int width = size.z; int height = size.y; _voxelSpace = new Voxel[length, width, height]; _XVoxelPlanes = new HashSet <Voxel> [length]; for (int i = 0; i < _XVoxelPlanes.Length; i++) { if (_XVoxelPlanes[i] == null) { _XVoxelPlanes[i] = new HashSet <Voxel>(); } else { _XVoxelPlanes[i].Clear(); } } _YVoxelPlanes = new HashSet <Voxel> [width]; for (int i = 0; i < _YVoxelPlanes.Length; i++) { if (_YVoxelPlanes[i] == null) { _YVoxelPlanes[i] = new HashSet <Voxel>(); } else { _YVoxelPlanes[i].Clear(); } } Vector3 origin = new Vector3( -((float)(length - 1) / 2f), -((float)(height - 1) / 2f), -((float)(width - 1) / 2f)); for (int x = 0; x < length; x++) { for (int y = 0; y < width; y++) { for (int z = 0; z < height; z++) { Vector3 thisPosition = origin; thisPosition.x += x; thisPosition.y += z; thisPosition.z += y; GameObject obj = Instantiate(voxelPrefab) as GameObject; obj.transform.SetParent(this.transform); obj.transform.localPosition = thisPosition; obj.transform.localScale = Vector3.one; Voxel vox = obj.GetComponent <Voxel>(); vox.State = GetState("Empty"); vox.point = new Point3(x, y, z); // Turn on reflections for edge voxels if (x == 0) { vox.WestRef = true; } if (x == length - 1) { vox.EastRef = true; } if (y == 0) { vox.SouthRef = true; } if (y == width - 1) { vox.NorthRef = true; } if (z == 0) { vox.BottomRef = true; } if (z == height - 1) { vox.TopRef = true; } _voxelSpace[x, y, z] = vox; } } } frameTransform.localScale = new Vector3(cubeSize, cubeSize, cubeSize); }
public void Interact() { if (Input.GetKeyDown(KeyCode.I) == true) { if (UIManager.hasInventoryOpen() == false) { UIManager.ShowInventory(GameMaster.Instance.player.getInventory()); } else { UIManager.CloseInventory(); } } if (Input.GetKeyDown(KeyCode.F) == true) { currentPaletteIndex = Util.WrapInt(currentPaletteIndex += 1, 2, Enum.GetValues(typeof(Voxel)).Length - 1); currentVoxel = (Voxel)currentPaletteIndex; UIManager.ForceUpdate(); } // Everything below here can't be done when mousing over non-clickthrough UI if (UIManager.isMouseOverUIWithIgnore() == true) { return; } Unity.Physics.RaycastHit hit; Unity.Entities.Entity hitEntity; hitData = null; if (GameMaster.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), 8, out hit, out hitEntity)) { hitData = new VoxelHitData(hit, hitEntity); Vector3 offsetPos = hitData.hitTransform.InverseTransformPoint(hit.Position); offsetPos.x = (float)Math.Round(offsetPos.x); offsetPos.y = (float)Math.Round(offsetPos.y); offsetPos.z = (float)Math.Round(offsetPos.z); // offsetPos.x = offsetPos.x - offsetPos.x % 1; // offsetPos.y = offsetPos.y - offsetPos.y % 1; // offsetPos.z = offsetPos.z - offsetPos.z % 1; offsetPos = hitData.hitTransform.rotation * offsetPos; Vector3 hitPos = hitData.hitTransform.position + offsetPos; Debug.DrawLine(Camera.main.ScreenPointToRay(Input.mousePosition).origin, hitPos, Color.red); Debug.DrawRay(hit.Position, hit.SurfaceNormal, Color.yellow); Debug.DrawRay(hit.Position, hit.SurfaceNormal * -0.5f, Color.cyan); } else { Debug.DrawRay(Camera.main.ScreenPointToRay(Input.mousePosition).origin, Camera.main.ScreenPointToRay(Input.mousePosition).direction * 8, Color.green); } // if (hit.collider != null) // { // Interactable interactable = hit.collider.GetComponent<Interactable>(); // if (interactable != null) // { // if (Input.GetMouseButtonDown(1) == true) // { // interactable.TryInteract(GameMaster.Instance.player.gameObject); // return; // } // else // { // interactable.TryHover(GameMaster.Instance.player.gameObject); // } // } // } Item mainHand = GameMaster.Instance.player.getEquipment().getSlot(EquipmentSlot.MAINHAND); if (mainHand.isValid() == false) { return; } if (Input.GetKeyDown(KeyCode.G) == true) { int amountToDrop = 1; if (Input.GetKey(KeyCode.LeftControl) == true || Input.GetKey(KeyCode.RightControl) == true) { amountToDrop = mainHand.getAmount(); } GameMaster.Instance.DropItemNaturally(Position.fromVector3(transform.position + (transform.forward * 3)), mainHand, amountToDrop); GameMaster.Instance.player.getInventory().Remove(mainHand, amountToDrop); } if (hitData == null || hitData.isValid() == false) { return; } if (mainHand is BLOCKITEM) { rotationOrientation = hitData.getFace().getOpposite(); currentVoxel = ((BLOCKITEM)mainHand).getVoxel(); if (Input.GetAxis("Mouse ScrollWheel") > 0) { rotationIndex = Util.WrapInt(rotationIndex += 1, 0, 3); rotationDirection = (Direction)rotationIndex; } else if (Input.GetAxis("Mouse ScrollWheel") < 0) { rotationIndex = Util.WrapInt(rotationIndex -= 1, 0, 3); rotationDirection = (Direction)rotationIndex; } if (Input.GetMouseButtonDown(1) == true) { if (hitData.getAtFace().getType() == Voxel.VOID) { Block thisBlock = hitData.voxelObject.setBlockAt(hitData.atFace, currentVoxel); if (thisBlock.getChunk() != null) { GameMaster.Instance.player.getInventory().Remove(mainHand, 1); GameMaster.Instance.PlaySound(placeSound, hit.Position); GetComponent <MotionAnimator>().PlayMotion("mainHandAttack"); if (thisBlock.getBlockData() is Rotatable) { Rotatable data = (Rotatable)thisBlock.getBlockData(); data.setDirection(rotationDirection); thisBlock.setBlockData(data); } if (thisBlock.getBlockData() is Orientated) { Orientated data = (Orientated)thisBlock.getBlockData(); data.setOrientation(rotationOrientation); thisBlock.setBlockData(data); } if (hitData.getFace() == Direction.BELOW) { if (thisBlock.getBlockData() is Flippable) { Flippable data = (Flippable)thisBlock.getBlockData(); data.setFlipped(true); thisBlock.setBlockData(data); } } } } } UpdateDisplayModel(); DrawDisplayModel(hitData.localFacePosition); } else if (mainHand is CUTTER) { Block clickedBlock = hitData.getAt(); if (Input.GetMouseButtonDown(0) == true) { if (clickedBlock.getType() != Voxel.VOID && clickedBlock.getType() != Voxel.SHIP_CORE) { Position droppedPosition = Position.fromVector3(hit.Position); GameMaster.Instance.DropItemNaturally(droppedPosition, clickedBlock.getType(), 1); Block thisBlock = hitData.voxelObject.setBlockAt(hitData.atHit, Voxel.VOID); if (thisBlock.getChunk() != null) { GameMaster.Instance.PlaySound(placeSound, hit.Position); GetComponent <MotionAnimator>().PlayMotion("mainHandAttack"); } } } else if (Input.GetMouseButtonDown(1) == true) { if (clickedBlock.getType() != Voxel.VOID && clickedBlock.getType() != Voxel.SHIP_CORE) { Block thisBlock = hitData.voxelObject.setBlockAt(hitData.atHit, Voxel.FRAME); if (thisBlock.getChunk() != null) { GameMaster.Instance.PlaySound(placeSound, hit.Position); GetComponent <MotionAnimator>().PlayMotion("mainHandAttack"); } } } currentVoxel = clickedBlock.getType(); if (clickedBlock.getBlockData() is Rotatable) { Rotatable data = (Rotatable)clickedBlock.getBlockData(); rotationDirection = data.getDirection(); } if (clickedBlock.getBlockData() is Orientated) { Orientated data = (Orientated)clickedBlock.getBlockData(); rotationOrientation = data.getOrientation(); } UpdateDisplayModel(); DrawDisplayModel(hitData.localPosition); } else if (mainHand is DRILL) { if (hitData.isValid()) { rotationOrientation = hitData.getFace().getOpposite(); if (Input.GetAxis("Mouse ScrollWheel") > 0) { rotationIndex = Util.WrapInt(rotationIndex += 1, 0, 3); rotationDirection = (Direction)rotationIndex; } else if (Input.GetAxis("Mouse ScrollWheel") < 0) { rotationIndex = Util.WrapInt(rotationIndex -= 1, 0, 3); rotationDirection = (Direction)rotationIndex; } if (Input.GetMouseButtonDown(2) == true) { Block clickedBlock = hitData.getAt(); if (clickedBlock.getType() != Voxel.VOID && clickedBlock.getType() != Voxel.SHIP_CORE) { currentVoxel = clickedBlock.getType(); currentPaletteIndex = (int)currentVoxel; } } if (Input.GetMouseButtonDown(1) == true) { if (hitData.getAt().getType() == Voxel.FRAME) { Block thisBlock = hitData.voxelObject.setBlockAt(hitData.atHit, currentVoxel); if (thisBlock.getChunk() != null) { GameMaster.Instance.PlaySound(placeSound, hit.Position); GetComponent <MotionAnimator>().PlayMotion("mainHandAttack"); if (thisBlock.getBlockData() is Rotatable) { Rotatable data = (Rotatable)thisBlock.getBlockData(); data.setDirection(rotationDirection); thisBlock.setBlockData(data); } if (thisBlock.getBlockData() is Orientated) { Orientated data = (Orientated)thisBlock.getBlockData(); data.setOrientation(rotationOrientation); thisBlock.setBlockData(data); } if (hitData.getFace() == Direction.BELOW) { if (thisBlock.getBlockData() is Flippable) { Flippable data = (Flippable)thisBlock.getBlockData(); data.setFlipped(true); thisBlock.setBlockData(data); } } } } } UpdateDisplayModel(); DrawDisplayModel(hitData.localPosition); } } }
private static int GetClusterFromVoxel(Voxel[,,] voxels, out NativeList <Cluster> Clusteres, out NativeList <Point> points, int vertexCount, int voxelSize) { bool deGenerated = (vertexCount % CLUSTERCLIPCOUNT == 0); int clusterCount = Mathf.CeilToInt((float)vertexCount / CLUSTERCLIPCOUNT); points = new NativeList <Point>(clusterCount * CLUSTERCLIPCOUNT, Allocator.Temp); Clusteres = new NativeList <Cluster>(clusterCount, Allocator.Temp); int index = 0; for (int i = 0; i < voxelSize; i++) { for (int j = 0; j < voxelSize; j++) { for (int k = 0; k < voxelSize; k++) { Voxel voxel = voxels[i, j, k]; if (voxel.count == 0) { continue; } while (voxel.count > 0) { Triangle tri = voxel.Pop(); points.Add(tri.a); points.Add(tri.b); points.Add(tri.c); index += 3; } } } } if (!deGenerated) { for (int i = vertexCount; i < clusterCount * CLUSTERCLIPCOUNT; i++) { points.Add(new Point()); } } float3 lessPoint; float3 morePoint; for (int i = 0; i < clusterCount; i++) { lessPoint = points[i * CLUSTERCLIPCOUNT].vertex; morePoint = points[i * CLUSTERCLIPCOUNT].vertex; for (int j = i * CLUSTERCLIPCOUNT; j < (i + 1) * CLUSTERCLIPCOUNT; j++) { lessPoint = lerp(lessPoint, points[j].vertex, (int3)(lessPoint > points[j].vertex)); morePoint = lerp(morePoint, points[j].vertex, (int3)(morePoint < points[j].vertex)); } Cluster cb = new Cluster { extent = (morePoint - lessPoint) / 2, position = (morePoint + lessPoint) / 2 }; Clusteres.Add(cb); } return(clusterCount); }
// Grab a single item from the storage box, and remmove it. public void GetItemFromContainer(TileEntityLootContainer tileLootContainer) { Ray lookRay = new Ray(this.theEntity.position, theEntity.GetLookVector()); if (!Voxel.Raycast(this.theEntity.world, lookRay, Constants.cDigAndBuildDistance, -538480645, 4095, 0f)) { return; // Not seeing the target. } if (!Voxel.voxelRayHitInfo.bHitValid) { return; // Missed the target. Overlooking? } Vector3i blockPos = tileLootContainer.ToWorldPos(); this.lstTileContainers.Remove(tileLootContainer); DisplayLog(" Loot List: " + tileLootContainer.lootListIndex); if (tileLootContainer.lootListIndex <= 0) { return; } if (tileLootContainer.bTouched) { return; } tileLootContainer.bTouched = true; tileLootContainer.bWasTouched = true; DisplayLog("Checking Loot Container"); if (tileLootContainer.items != null) { BlockValue block = this.theEntity.world.GetBlock(blockPos); String lootContainerName = Localization.Get(Block.list[block.type].GetBlockName(), string.Empty); theEntity.SetLookPosition(blockPos.ToVector3()); DisplayLog(" Loot container is: " + lootContainerName); DisplayLog(" Loot Container has this many Slots: " + tileLootContainer.items.Length); EntityPlayer player = null; if (this.theEntity.Buffs.HasCustomVar("Leader")) { player = theEntity.world.GetEntity((int)this.theEntity.Buffs.GetCustomVar("Leader")) as EntityPlayerLocal; } theEntity.MinEventContext.TileEntity = tileLootContainer; theEntity.FireEvent(MinEventTypes.onSelfOpenLootContainer); UnityEngine.Random.State state = UnityEngine.Random.state; UnityEngine.Random.InitState((int)(GameManager.Instance.World.worldTime % 2147483647UL)); ItemStack[] array = LootContainer.lootList[tileLootContainer.lootListIndex].Spawn(tileLootContainer.items.Length, EffectManager.GetValue(PassiveEffects.LootGamestage, null, (float)player.PartyGameStage, player, null, default(FastTags), true, true, true, true), 0f); UnityEngine.Random.state = state; for (int i = 0; i < array.Length; i++) { if (this.theEntity.lootContainer.AddItem(array[i].Clone())) { DisplayLog("Removing item from loot container: " + array[i].itemValue.ItemClass.Name); } else { DisplayLog(" Could Not add Item to NPC inventory. " + tileLootContainer.items[i].itemValue.ToString()); if (theEntity is EntityAliveSDX) { (theEntity as EntityAliveSDX).ExecuteCMD("Follow", player); return; } } } theEntity.FireEvent(MinEventTypes.onSelfLootContainer); } }
public static void Explode(Main main, Voxel map, Voxel.Coord coord, int radius = 8, float physicsRadius = 12.0f) { Vector3 pos = map.GetAbsolutePosition(coord); Explosion.explode(main, map, coord, pos, radius, physicsRadius); }
private static void explode(Main main, Voxel map, Voxel.Coord coord, Vector3 pos, int radius, float physicsRadius) { // Kaboom AkSoundEngine.PostEvent(AK.EVENTS.PLAY_EXPLOSION, pos); Entity lightEntity = Factory.Get <PointLightFactory>().CreateAndBind(main); lightEntity.Serialize = false; PointLight light = lightEntity.Get <PointLight>(); light.Color.Value = new Vector3(1.3f, 1.1f, 0.9f); light.Attenuation.Value = 20.0f; light.Position.Value = pos; lightEntity.Add(new Animation ( new Animation.FloatMoveTo(light.Attenuation, 0.0f, 1.0f), new Animation.Execute(light.Delete) )); main.Add(lightEntity); SmokeFactory smokeFactory = Factory.Get <SmokeFactory>(); for (int i = 0; i < 5; i++) { Entity smoke = smokeFactory.CreateAndBind(main); smoke.Get <Transform>().Position.Value = pos; main.Add(smoke); } ParticleEmitter.Emit(main, "Smoke", pos, physicsRadius * 0.4f, 250); Entity player = PlayerFactory.Instance; if (player != null && player.Active) { player.Get <CameraController>().Shake.Execute(pos, 50.0f); } const float physicsImpulse = 70.0f; const float minPlayerDamage = 0.1f; const float playerDamageMultiplier = 2.0f; // Remove the cells BlockFactory blockFactory = Factory.Get <BlockFactory>(); foreach (Voxel m in Voxel.ActiveVoxels.ToList()) { List <Voxel.Coord> removals = new List <Voxel.Coord>(); Voxel.Coord c = m.GetCoordinate(pos); Vector3 relativePos = m.GetRelativePosition(c); Quaternion quat = m.Entity.Get <Transform>().Quaternion; for (Voxel.Coord x = c.Move(Direction.NegativeX, radius - 1); x.X < c.X + radius; x.X++) { for (Voxel.Coord y = x.Move(Direction.NegativeY, radius - 1); y.Y < c.Y + radius; y.Y++) { for (Voxel.Coord z = y.Move(Direction.NegativeZ, radius - 1); z.Z < c.Z + radius; z.Z++) { Voxel.State s = m[z]; if (s.ID == 0 || s.Permanent) { continue; } Vector3 cellPos = m.GetRelativePosition(z); if ((cellPos - relativePos).Length() < radius - 1) { removals.Add(z); if (random.NextDouble() > 0.5) { Entity block = blockFactory.CreateAndBind(main); Transform blockTransform = block.Get <Transform>(); blockTransform.Position.Value = m.GetAbsolutePosition(cellPos); blockTransform.Quaternion.Value = quat; s.ApplyToBlock(block); main.Add(block); } } } } } if (removals.Count > 0) { m.Empty(removals); m.Regenerate(); } } // Damage the player if (player != null && player.Active) { Vector3 toPlayer = player.Get <Transform>().Position - pos; float d = toPlayer.Length(); if (d < physicsRadius) { float attenuation = 1.0f; if (d > 0) { Voxel.GlobalRaycast(pos, toPlayer / d, d, delegate(int x, Voxel.t c) { Voxel.State s = Voxel.States.All[c]; if (s.Permanent) { attenuation = 0.0f; return(true); } else if (s.Hard) { attenuation -= 0.6f; } else { attenuation -= 0.35f; } return(false); }); attenuation = Math.Max(0, attenuation); } player.Get <Agent>().Damage.Execute(attenuation * (minPlayerDamage + (1.0f - (d / physicsRadius)) * playerDamageMultiplier)); } } // Apply impulse to dynamic maps foreach (Voxel m in Voxel.ActiveVoxels) { DynamicVoxel dm = m as DynamicVoxel; if (dm == null) { continue; } Vector3 toMap = dm.Transform.Value.Translation - pos; float distanceToMap = toMap.Length(); toMap /= distanceToMap; toMap *= Math.Max(0.0f, 1.0f - (distanceToMap / physicsRadius)) * Math.Min(200.0f, dm.PhysicsEntity.Mass) * physicsImpulse; dm.PhysicsEntity.ApplyImpulse(dm.Transform.Value.Translation + new Vector3(((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f), toMap); } // Apply impulse to physics blocks foreach (Entity b in main.Get("Block")) { PhysicsBlock block = b.Get <PhysicsBlock>(); Vector3 fromExplosion = b.Get <Transform>().Position.Value - pos; float distance = fromExplosion.Length(); if (distance > 0.0f && distance < physicsRadius) { float blend = 1.0f - (distance / physicsRadius); block.LinearVelocity.Value += fromExplosion * blend * 10.0f / distance; block.AngularVelocity.Value += new Vector3(((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f, ((float)random.NextDouble() - 0.5f) * 2.0f) * blend; } } }
public BrushHit(Voxel voxel, float influence) { this.voxel = voxel; this.influence = influence; }
private float[] CalculateMaterialAmountsBetween(int[] materialIds, Voxel voxel1, Voxel voxel2) { float[] materialAmounts = new float[materialIds.Length]; float addedFillingQuantity = voxel1.FillingQuantity + voxel2.FillingQuantity; for (int i = 0; i < materialIds.Length; i++) { materialAmounts[i] = 0; if (materialIds[i] == voxel1.MaterialId) { materialAmounts[i] += voxel1.FillingQuantity / addedFillingQuantity; } if (materialIds[i] == voxel2.MaterialId) { materialAmounts[i] += voxel2.FillingQuantity / addedFillingQuantity; } } return(materialAmounts); }
public void DoOperation(Voxel node, FuncPtr func) { func(node); }
void RemoveVisible(Voxel node) { DestroyImmediate(node.visible); node.visible = null; }
void Update() { if (!gameManager.IsPaused) { // Panning. float translationX = Input.GetAxis("Horizontal") * panSpeed * Time.deltaTime; float translationZ = Input.GetAxis("Vertical") * panSpeed * Time.deltaTime; int previousYPosition = CurrentYPosition; int previousYUpperBound = CurrentYUpperBound; // For SliceRenderMode.Adaptive if (translationX != 0 || translationZ != 0) { transform.Translate(translationX, 0, translationZ, Space.Self); float posX = transform.position.x; float posZ = transform.position.z; // Constrain to map. if (transform.position.x < minXZ) { posX = minXZ; } else if (transform.position.x > maxXZ) { posX = maxXZ; } if (transform.position.z < minXZ) { posZ = minXZ; } else if (transform.position.z > maxXZ) { posZ = maxXZ; } transform.position = new Vector3(posX, transform.position.y, posZ); if (Map.SliceRenderMode == SliceRenderMode.Adaptive) { Voxel v = Map.GetVoxelCameraFocusCoordinates(posX, CurrentYPosition, posZ); CurrentYUpperBound = Map.FindDistanceToFirstNonTransparentVoxel(Direction.Up, v); } // Rendering in slice mode only forces adjustments when traversing y levels. if (Map.SliceRenderMode == SliceRenderMode.Slice && previousYPosition != CurrentYPosition) { Map.SetSlicesAboveYHidden(CurrentYPosition + Map.YOffset); Map.SetSlicesOnAndBelowYVisible(CurrentYPosition + Map.YOffset); Map.RebuildQueuedSlicesOnY(CurrentYPosition + Map.YOffset); // Rebuild all visible instead. } // Rendering in adaptive mode forces adjustments when traversing y levels or moving on the x,z. if (Map.SliceRenderMode == SliceRenderMode.Adaptive && previousYPosition != CurrentYPosition || previousYUpperBound != CurrentYUpperBound) { Map.SetSlicesAboveYHidden(CurrentYPosition + CurrentYUpperBound + Map.YOffset); Map.SetSlicesOnAndBelowYVisible(CurrentYPosition + CurrentYUpperBound + Map.YOffset); Map.RebuildQueuedSlicesOnY(CurrentYPosition + CurrentYUpperBound + Map.YOffset); } if (Map.SliceRenderMode == SliceRenderMode.Full) // SOMETHING IS CAUSING A VISUAL PULSATION BUG HERE. { if (Map.VisibleSlices.Count != Map.Instance.Slices.Length) { Map.SetSlicesOnAndBelowYVisible((int)maxY); } Map.RebuildQueuedSlices(); // This should be left to the regular update call for rebuilding. } } // Rotating. if (Input.GetKeyUp(rotateCounterClockwiseKey)) { transform.Rotate(0, degreesToRotate, 0, Space.World); } if (Input.GetKeyUp(rotateClockwiseKey)) { transform.Rotate(0, -degreesToRotate, 0, Space.World); } // Zooming and slice traversal. float translationY = Input.GetAxis("Mouse ScrollWheel"); if (translationY != 0) { // Zooming. if (Input.GetKey(zoomKey)) { translationY *= zoomSpeed * Time.deltaTime; float posY = mainCamera.transform.localPosition.y - translationY; // Constrain to zoom limits. if (posY > maxZoomOut) { posY = maxZoomOut; } else if (posY < maxZoomIn) { posY = maxZoomIn; } mainCamera.transform.localPosition = new Vector3(0, posY, 0); } // Fast slice traversal. else if (Input.GetKey(fastYTraversalKey)) { if (translationY > 0) { translationY = (FasterYSliceSpeed * Map.VoxelFloorHeight) + FasterYSliceSpeed; CurrentYPosition += (int)FasterYSliceSpeed; } else { translationY = -(FasterYSliceSpeed * Map.VoxelFloorHeight) - FasterYSliceSpeed; CurrentYPosition -= (int)FasterYSliceSpeed; } // Constrain to map. float posY = transform.position.y + translationY; if (posY < minY) { posY = minY; CurrentYPosition = -Map.YOffset; } else if (posY > maxY) { posY = maxY; CurrentYPosition = Map.YOffset - 1; } transform.position = new Vector3(transform.position.x, posY, transform.position.z); // For SliceRenderMode.Adaptive mode. if (Map.SliceRenderMode == SliceRenderMode.Adaptive) { Voxel v = Map.GetVoxelCameraFocusCoordinates(transform.position.x, CurrentYPosition, transform.position.z); CurrentYUpperBound = Map.FindDistanceToFirstNonTransparentVoxel(Direction.Up, v); } } // Regular slice traversal. else { if (translationY > 0) { translationY = 1.0f + Map.VoxelFloorHeight; CurrentYPosition += 1; } else { translationY = -1.0f - Map.VoxelFloorHeight; CurrentYPosition -= 1; } // Constrain to map. float posY = transform.position.y + translationY; if (posY < minY) { posY = minY; CurrentYPosition = -Map.YOffset; } else if (posY > maxY) { posY = maxY; CurrentYPosition = Map.YOffset - 1; } transform.position = new Vector3(transform.position.x, posY, transform.position.z); if (Map.SliceRenderMode == SliceRenderMode.Adaptive) { // For SliceRenderMode.Adaptive mode. Voxel v = Map.GetVoxelCameraFocusCoordinates(transform.position.x, CurrentYPosition, transform.position.z); CurrentYUpperBound = Map.FindDistanceToFirstNonTransparentVoxel(Direction.Up, v); } } Debug.Log(CurrentYPosition); // Rendering in slice mode only forces adjustments when traversing y levels. if (Map.SliceRenderMode == SliceRenderMode.Slice) { Map.SetSlicesAboveYHidden(CurrentYPosition + Map.YOffset); Map.SetSlicesOnAndBelowYVisible(CurrentYPosition + Map.YOffset); Map.RebuildQueuedSlicesOnY(CurrentYPosition + Map.YOffset); } // Rendering in adaptive mode forces adjustments when traversing y levels or moving on the x,z. if (Map.SliceRenderMode == SliceRenderMode.Adaptive && previousYPosition != CurrentYPosition || previousYUpperBound != CurrentYUpperBound) { Map.SetSlicesAboveYHidden(CurrentYPosition + CurrentYUpperBound + Map.YOffset); Map.SetSlicesOnAndBelowYVisible(CurrentYPosition + CurrentYUpperBound + Map.YOffset); Map.RebuildQueuedSlicesOnY(CurrentYPosition + CurrentYUpperBound + Map.YOffset); } if (Map.SliceRenderMode == SliceRenderMode.Full) { if (Map.VisibleSlices.Count != Map.Instance.Slices.Length) { Map.SetSlicesOnAndBelowYVisible((int)maxY); } Map.RebuildQueuedSlices(); // This should be left to the regular update call for rebuilding. } } } }
public override void Bind(Entity entity, Main main, bool creating = false) { SpotLight light = entity.Create <SpotLight>(); light.Enabled.Value = !main.EditorEnabled; light.FieldOfView.Value = 1.0f; light.Attenuation.Value = 75.0f; Transform transform = entity.GetOrCreate <Transform>("Transform"); light.Add(new Binding <Vector3>(light.Position, transform.Position)); light.Add(new Binding <Quaternion>(light.Orientation, transform.Quaternion)); Turret turret = entity.GetOrCreate <Turret>("Turret"); Command die = new Command { Action = delegate() { AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_DEATH, entity); ParticleSystem shatter = ParticleSystem.Get(main, "InfectedShatter"); Random random = new Random(); for (int i = 0; i < 50; i++) { Vector3 offset = new Vector3((float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f); shatter.AddParticle(transform.Position + offset, offset); } entity.Delete.Execute(); } }; VoxelAttachable attachable = VoxelAttachable.MakeAttachable(entity, main, true, true, die); attachable.Enabled.Value = true; attachable.Offset.Value = 2; PointLight pointLight = entity.GetOrCreate <PointLight>(); pointLight.Serialize = false; pointLight.Add(new Binding <Vector3>(pointLight.Position, transform.Position)); LineDrawer laser = new LineDrawer { Serialize = false }; entity.Add(laser); AI ai = entity.GetOrCreate <AI>("AI"); ModelAlpha model = entity.Create <ModelAlpha>(); model.Add(new Binding <Matrix>(model.Transform, transform.Matrix)); model.Filename.Value = "AlphaModels\\pyramid"; const float defaultModelScale = 0.75f; model.Scale.Value = new Vector3(defaultModelScale); const float sightDistance = 80.0f; const float hearingDistance = 20.0f; const float operationalRadius = 100.0f; model.Add(new Binding <Vector3, string>(model.Color, delegate(string state) { switch (state) { case "Alert": return(new Vector3(1.5f, 1.5f, 0.5f)); case "Aggressive": return(new Vector3(1.5f, 0.8f, 0.5f)); case "Firing": return(new Vector3(2.0f, 0.0f, 0.0f)); case "Disabled": return(new Vector3(0.0f, 0.0f, 0.0f)); default: return(new Vector3(1.0f, 1.0f, 1.0f)); } }, ai.CurrentState)); laser.Add(new Binding <bool, string>(laser.Enabled, x => x != "Disabled" && x != "Suspended", ai.CurrentState)); light.Add(new Binding <Vector3>(light.Color, model.Color)); pointLight.Add(new Binding <Vector3>(pointLight.Color, model.Color)); Voxel.GlobalRaycastResult rayHit = new Voxel.GlobalRaycastResult(); Vector3 toReticle = Vector3.Zero; AI.Task checkOperationalRadius = new AI.Task { Interval = 2.0f, Action = delegate() { bool shouldBeActive = (transform.Position.Value - main.Camera.Position).Length() < operationalRadius && !Water.IsSubmerged(transform.Position); if (shouldBeActive && ai.CurrentState == "Suspended") { ai.CurrentState.Value = "Idle"; } else if (!shouldBeActive && ai.CurrentState != "Suspended") { ai.CurrentState.Value = "Suspended"; } }, }; turret.Add(new CommandBinding(turret.PowerOn, delegate() { if (ai.CurrentState == "Disabled") { ai.CurrentState.Value = "Suspended"; checkOperationalRadius.Action(); } })); turret.Add(new CommandBinding(turret.PowerOff, delegate() { ai.CurrentState.Value = "Disabled"; })); AI.Task updateRay = new AI.Task { Action = delegate() { toReticle = Vector3.Normalize(turret.Reticle.Value - transform.Position.Value); rayHit = Voxel.GlobalRaycast(transform.Position, toReticle, operationalRadius); laser.Lines.Clear(); Microsoft.Xna.Framework.Color color = new Microsoft.Xna.Framework.Color(model.Color); laser.Lines.Add(new LineDrawer.Line { A = new Microsoft.Xna.Framework.Graphics.VertexPositionColor(transform.Position, color), B = new Microsoft.Xna.Framework.Graphics.VertexPositionColor(rayHit.Position, color), }); } }; ai.Add(new AI.AIState { Name = "Disabled", Tasks = new AI.Task[] { }, }); ai.Add(new AI.AIState { Name = "Suspended", Tasks = new[] { checkOperationalRadius, }, }); ai.Add(new AI.AIState { Name = "Idle", Tasks = new[] { checkOperationalRadius, updateRay, new AI.Task { Interval = 1.0f, Action = delegate() { Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player"); if (a != null) { ai.CurrentState.Value = "Alert"; } }, }, }, }); ai.Add(new AI.AIState { Name = "Alert", Tasks = new[] { checkOperationalRadius, updateRay, new AI.Task { Interval = 1.0f, Action = delegate() { if (ai.TimeInCurrentState > 3.0f) { ai.CurrentState.Value = "Idle"; } else { Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player"); if (a != null) { ai.TargetAgent.Value = a.Entity; ai.CurrentState.Value = "Aggressive"; } } }, }, }, }); AI.Task checkTargetAgent = new AI.Task { Action = delegate() { Entity target = ai.TargetAgent.Value.Target; if (target == null || !target.Active) { ai.TargetAgent.Value = null; ai.CurrentState.Value = "Idle"; } }, }; float lastSpotted = 0.0f; ai.Add(new AI.AIState { Name = "Aggressive", Tasks = new[] { checkTargetAgent, updateRay, new AI.Task { Action = delegate() { Entity target = ai.TargetAgent.Value.Target; turret.Reticle.Value += (target.Get <Transform>().Position - turret.Reticle.Value) * Math.Min(3.0f * main.ElapsedTime, 1.0f); } }, new AI.Task { Interval = 0.1f, Action = delegate() { if (Agent.Query(transform.Position, sightDistance, hearingDistance, ai.TargetAgent.Value.Target.Get <Agent>())) { lastSpotted = main.TotalTime; } if (ai.TimeInCurrentState.Value > 1.5f) { if (lastSpotted < main.TotalTime - 2.0f) { ai.CurrentState.Value = "Alert"; } else { Vector3 targetPos = ai.TargetAgent.Value.Target.Get <Transform>().Position.Value; Vector3 toTarget = Vector3.Normalize(targetPos - transform.Position.Value); if (Vector3.Dot(toReticle, toTarget) > 0.95f) { ai.CurrentState.Value = "Firing"; } } } } }, } }); ai.Add(new AI.AIState { Name = "Firing", Enter = delegate(AI.AIState last) { AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_CHARGE, entity); }, Exit = delegate(AI.AIState next) { Voxel.State attachedState = attachable.AttachedVoxel.Value.Target.Get <Voxel>()[attachable.Coord]; if (!attachedState.Permanent && rayHit.Voxel != null && (rayHit.Position - transform.Position).Length() < 8.0f) { return; // Danger close, cease fire! } AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_FIRE, entity); bool hitVoxel = true; Entity target = ai.TargetAgent.Value.Target; if (target != null && target.Active) { Vector3 targetPos = target.Get <Transform>().Position; Vector3 toTarget = targetPos - transform.Position.Value; if (Vector3.Dot(toReticle, Vector3.Normalize(toTarget)) > 0.2f) { float distance = toTarget.Length(); if (distance < rayHit.Distance) { AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_MISS, transform.Position + toReticle * distance); } } BEPUutilities.RayHit physicsHit; if (target.Get <Player>().Character.Body.CollisionInformation.RayCast(new Ray(transform.Position, toReticle), rayHit.Voxel == null ? float.MaxValue : rayHit.Distance, out physicsHit)) { Explosion.Explode(main, targetPos, 6, 8.0f); hitVoxel = false; } } if (hitVoxel && rayHit.Voxel != null) { Explosion.Explode(main, rayHit.Position + rayHit.Voxel.GetAbsoluteVector(rayHit.Normal.GetVector()) * 0.5f, 6, 8.0f); } }, Tasks = new[] { checkTargetAgent, updateRay, new AI.Task { Action = delegate() { if (ai.TimeInCurrentState.Value > 0.75f) { ai.CurrentState.Value = "Aggressive"; // This actually fires (in the Exit function) } } } } }); this.SetMain(entity, main); entity.Add("On", turret.On); entity.Add("PowerOn", turret.PowerOn); entity.Add("PowerOff", turret.PowerOff); }
public void createVoxelContainer(Voxel majorVoxel) { if (majorVoxel == null) { Debug.LogError("trying to create a voxel container from a null or deleted voxel"); return; } Mesh majorMesh = majorVoxel.filter.mesh; if (majorVoxel.deletedPoints == null) { Debug.LogError("trying to create voc container with non nul voxel which has a null or deleted points array"); } if (majorMesh == null) { Debug.LogError("cannot extract mesh from vox " + majorVoxel + " ;" + majorVoxel.gameObject + " while trying to create voxel container"); } if (majorVoxel.deletedPoints == null || majorVoxel.deletedPoints.Count == 0 || shatterSmoothedVoxels) { //is a full voxel //need to construct 6 submeshes using the major mesh data Vector3[] centerPoints = getCenterPoints(majorMesh, majorVoxel); //0 bottom; 1 middle; 2 top randDev = new float[] { (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble() }; //for (int i = 0; i < (shatterLevel == 0 ? 6 : 8); i++)//for the 6 split first then the 8 split for (int i = 0; i < (majorVoxel.shatterLevel == 0?8:4); i++)// for the 8 split both times //for (int i = 0; i < (shatterLevel == 0 ? 8 : 4); i++)//for the 8 split then the 4 split(8split without cutting the voxel depth in two) { //sub mesh i is the triangle that goes from vert i -> vert [(i+1)%3+ (i > 2 ? 3 : 0)] -> center - 0,1,2 is bottom 3 4,5,6 is top 3 GameObject subVoxelObject = genNewSubVoxel(); Voxel subVoxelScript = subVoxelObject.GetComponent <Voxel>(); MeshFilter subMesh = subVoxelObject.GetComponent <MeshFilter>(); Vector3[] verts = getSubMesh(majorMesh, centerPoints, i, shatterLevel, majorVoxel); subMesh.mesh.vertices = verts; if (majorVoxel.shatterLevel > 0 && i == 3) { subMesh.mesh.triangles = getTriangles(i, !majorVoxel.isBottom); } else { subMesh.mesh.triangles = getTriangles(i, majorVoxel.isBottom); } //Debug.Log("binding i=" + i + " triangles : " + subMesh.mesh.triangles[0] + " ; " + subMesh.mesh.triangles[1] + " ; " + subMesh.mesh.triangles[2] + " ; " + subMesh.mesh.triangles[3] + " ; " + subMesh.mesh.triangles[4] + " ; " + subMesh.mesh.triangles[5] + " ; "); subMesh.name = "subVoxelShape"; subMesh.mesh.uv = new[] { new Vector2(0.3f, 0.4f), new Vector2(0.5f, 0.4f), new Vector2(0.5f, 0.6f), new Vector2(0.1f, 0.6f), new Vector2(0.1f, 0.9f), new Vector2(0.4f, 0.9f) }; subMesh.mesh.RecalculateNormals(); subVoxelObject.GetComponent <MeshCollider>().sharedMesh = subMesh.mesh; subVoxelScript.layer = majorVoxel.layer; subVoxelScript.columnID = majorVoxel.columnID; subVoxelScript.centreOfObject = getCentrePoint(verts); //subVoxelScript.info += "sub i=" + i; subVoxelScript.shatterLevel = majorVoxel.shatterLevel + 1; subVoxelScript.isBottom = i > 2 && i <= 5 || (i == 7 && !majorVoxel.isBottom) || (i == 6 && majorVoxel.isBottom); //subVoxelScript.isBottom = subVoxelScript.isBottom; subVoxelScript.subVoxelID = majorVoxel.subVoxelID + "," + i; subVoxelScript.info += "id: " + (subVoxelScript.subVoxelID); subVoxelScript.hasEnergy = majorVoxel.hasEnergy; subVoxelScript.isCaveFloor = majorVoxel.isCaveFloor; subVoxelScript.isCaveBorder = majorVoxel.isCaveBorder; subVoxelScript.isCaveCeiling = majorVoxel.isCaveCeiling; subVoxelScript.shatterCap = majorVoxel.shatterCap; subVoxelScript.filter = subMesh; subVoxelScript.deletedPoints = new HashSet <int>(); //Instantiate(subVoxelObject); double scale = Math.Pow(scaleRatio, Math.Abs(layer)); subVoxelScript.worldCentreOfObject = subVoxelScript.centreOfObject * (float)scale * MapManager.mapSize; //Debug.Log("scaling up subVoxel from " + subVoxelObject.transform.localScale + " to " + (Vector3.one * (float)scale)); subVoxelObject.transform.localScale = Vector3.one * (float)scale * MapManager.mapSize; //subVoxelObject.transform.parent = gameObject.transform; subVoxels.Add(subVoxelScript); subVoxelScript.checkTriangleNorms(5); if (isServer) { NetworkServer.Spawn(subVoxelObject); } } } layer = majorVoxel.layer; columnID = majorVoxel.columnID; }