void Start() { voxelizer = new Voxelizer(particleDiameter); var mesh = GetComponent <MeshFilter>().mesh; voxelizer.Build(mesh, conservative); }
void Start() { voxels = Voxelizer.Voxelize(mesh, count); voxels.ForEach(voxel => { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.parent = transform; cube.transform.localPosition = voxel.position; cube.transform.localScale = voxel.size * Vector3.one; cube.transform.localRotation = Quaternion.identity; }); }
public override void LoadContent() { InputManager.LockMouseToCenter = true; game.IsMouseVisible = false; VoxelRenderer.Init(Game); Voxelizer.Init(); cameraPosition = new Vector3(25, 50, 150); chunk = Voxelizer.CreateChunk(0.5f); marker = new SpherePrimitive(8, 16); }
public override void OnInspectorGUI() { DrawDefaultInspector(); Voxelizer octreeBuilder = (Voxelizer)target; if (GUILayout.Button("Bake Octree!")) { octreeBuilder.BAKE_OCTREE(); } if (GUILayout.Button("Delete Octree!")) { octreeBuilder.DeleteOctree(); } }
void OnEnable() { _resolution = (int)resolution; _camera = GetComponent <Camera>(); _command = new CommandBuffer { name = "VXGI" }; _mipmapper = new Mipmapper(this); _parameterizer = new Parameterizer(); _voxelizer = new Voxelizer(this); _voxelShader = new VoxelShader(this); _lastVoxelSpaceCenter = voxelSpaceCenter; CreateBuffers(); CreateTextureDescriptor(); CreateTextures(); }
/* * public int height; * public Mesh testMesh; * public Texture2D testTex; * public bool isDebug = false; * * private void Start() * { * if (isDebug) * { * BrickItConfiguration testCFG = GetTestCfg(); * runBrickification(testCFG); * } * }*/ public List <BuildingBlock> GetBuildingBlocks(BrickItConfiguration cfg) { var oldMesh = cfg.mesh.vertices; if (lastBricked != null) { DestroyImmediate(lastBricked); lastBricked = null; } BlockSelector selector = new BlockSelector(cfg.brickExtends); var tex = ColorCalculation.colorCalculate(cfg.tex, cfg.colors); var voxels = Voxelizer.Voxelize(cfg.mesh, tex, cfg.height); voxels = Voxelizer.AddWidth(voxels, cfg.depth); lastExtends = MeshUtils.GetBoundsPerDimension(cfg.mesh); cfg.mesh.vertices = oldMesh; cfg.mesh.RecalculateBounds(); return(selector.calculateBlocksSpiralWithBounds(voxels)); }
void OnEnable() { _resolution = (int)resolution; _camera = GetComponent <Camera>(); _command = new CommandBuffer { name = "VXGI.MonoBehaviour" }; _lights = new List <LightSource>(64); _lightSources = new ComputeBuffer(64, LightSource.size); _mipmapper = new Mipmapper(this); _parameterizer = new Parameterizer(); _voxelizer = new Voxelizer(this); _voxelShader = new VoxelShader(this); _lastVoxelSpaceCenter = voxelSpaceCenter; CreateBuffers(); CreateTextureDescriptor(); CreateTextures(); }
public static void ShowVoxelGrid(VoxelGrid grid) { var game = new DX11Game(); game.InitDirectX(); var renderer = new DeferredRenderer(game); var light = renderer.CreateDirectionalLight(); var ret = grid; IMesh voxelMesh = Voxelizer.CreateVoxelMesh(ret); var voxel = renderer.CreateMeshElement(voxelMesh); voxel.WorldMatrix = Matrix.Translation(0, 0, 0); game.GameLoopEvent += delegate { renderer.Draw(); }; game.Run(); }
public void TestVoxelizeMesh() { var game = new DX11Game(); game.InitDirectX(); var renderer = new DeferredRenderer(game); var light = renderer.CreateDirectionalLight(); var mesh = OBJParserTest.GetBarrelMesh(new TheWizards.OBJParser.OBJToRAMMeshConverter(new RAMTextureFactory())); var position = mesh.GetCoreData().Parts[0].MeshPart.GetGeometryData().GetSourceVector3( MeshPartGeometryData.Semantic.Position); var positions = new Vector3[position.Length]; for (int i = 0; i < position.Length; i++) { positions[i] = position[i].dx(); } var builder = new MeshBuilder(); var voxelizer = new Voxelizer(); var resolution = 0.01f; var ret = voxelizer.Voxelize(mesh, resolution); var scale = 3; for (int x = ret.Min.X; x <= ret.Max.X; x++) { for (int y = ret.Min.Y; y <= ret.Max.Y; y++) { for (int z = ret.Min.Z; z <= ret.Max.Z; z++) { if (!ret[x, y, z]) { continue; } builder.AddBox(new Vector3(x, y, z) * resolution * scale, (new Vector3(x, y, z) + MathHelper.One) * resolution * scale); } } } IMesh voxelMesh = builder.CreateMesh(); var ori = renderer.CreateMeshElement(mesh); ori.WorldMatrix = Matrix.Scaling(MathHelper.One * scale) * Matrix.Translation(0, 0, 0); var voxel = renderer.CreateMeshElement(voxelMesh); voxel.WorldMatrix = Matrix.Translation(0, 0, 0); game.GameLoopEvent += delegate { renderer.Draw(); }; game.Run(); }
public void OnGUI() { if (onProcessing) { return; } GUI.depth = 10; GUI.enabled = false; objPath = GUI.TextField(new Rect(10, 10, 300, 20), objPath); GUI.enabled = true; if (GUI.Button(new Rect(310, 10, 20, 20), "...")) { OpenFileName ofn = new OpenFileName(); ofn.structSize = Marshal.SizeOf(ofn); ofn.filter = "Object Files (*.obj)\0*.obj\0\0"; ofn.file = new string(new char[256]); ofn.maxFile = ofn.file.Length; ofn.fileTitle = new string(new char[64]); ofn.maxFileTitle = ofn.fileTitle.Length; ofn.initialDir = UnityEngine.Application.dataPath; ofn.title = "Select Object"; ofn.defExt = "OBJ"; //显示文件的类型 ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008; //OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR // ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008; if (DllTest.GetOpenFileName(ofn)) { // StartCoroutine(WaitLoad(ofn.file));//加载图片到panle objPath = ofn.file; Debug.Log("Selected file with full path: " + ofn.file); } /* * if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK){ * objPath = openFileDialog.FileName; * }else{ * objPath=""; * } */ //objPath = EditorUtility.OpenFilePanel("Please select an object file","","obj"); Debug.Log(objPath); } if (GUI.Button(new Rect(10, 40, 100, 20), "import")) { hasLegoized = false; if (objPath == "") { MessageBox.Show("You Must Select an Object first!", "Select Object"); /*EditorUtility.DisplayDialog( * "Select Object", * "You Must Select an Object first!", * "Ok");*/ return; } else { isObjectLoaded = false; Destroy(GetComponent("MeshFilter")); Destroy(GetComponent("MeshRenderer")); Destroy(GetComponent("MeshCollider")); GameObject voxelContainer = GameObject.Find("Voxelized"); GameObject legoContainer = GameObject.Find("Legoizer"); StartCoroutine(removeVoxels(voxelContainer)); StartCoroutine(removeVoxels(legoContainer)); buffer = new GeometryBuffer(); mtllib = ""; StartCoroutine(Load("file:///" + objPath)); } } GUI.enabled = isObjectLoaded; GUI.Label(new Rect(10, 70, 220, 20), "Sample Resolution (1000-8000000): "); samplingResolutionStr = GUI.TextField(new Rect(230, 70, 100, 20), samplingResolutionStr, 25); samplingResolutionStr = Regex.Replace(samplingResolutionStr, "[^0-9]", ""); sampleResoultion = int.Parse(samplingResolutionStr); colorMode = GUI.SelectionGrid(new Rect(10, 100, 220, 20), colorMode, colorModes, colorModes.Length, GUI.skin.toggle); if (GUI.Button(new Rect(10, 130, 100, 20), "Legoize")) { hasLegoized = false; if (sampleResoultion < 1001 || sampleResoultion > 8000000) { MessageBox.Show("The sample resolution must be in between 1000 to 8000000", "Out of Range"); /*EditorUtility.DisplayDialog( * "Out of Range", * "The sample resolution must be in between 1000 to 8000000", * "Ok");*/ return; } GameObject voxelContainer = GameObject.Find("Voxelized"); GameObject legoContainer = GameObject.Find("Legoizer"); while (voxelContainer.transform.childCount > 0) { GameObject.DestroyImmediate(voxelContainer.transform.GetChild(0).gameObject); } while (legoContainer.transform.childCount > 0) { GameObject.DestroyImmediate(legoContainer.transform.GetChild(0).gameObject); } Resources.UnloadUnusedAssets(); System.GC.Collect(); Voxelizer voxelizer = GameObject.Find("Voxelized").GetComponent <Voxelizer> (); StartCoroutine(voxelizer.voxelize()); } GUI.enabled = true; if (hasLegoized) { if (GUI.Button(new Rect(10, 160, 100, 20), "Save")) { LxfmlWriter xmlWriter = GameObject.Find("FileWriter").GetComponent <LxfmlWriter> (); StartCoroutine(xmlWriter.writeXML(legos)); } } }
private void Awake() { Instance = this; }
private void Update() { if (undo) { undo = false; var editManager = GetComponent <VoxelEditManagerContainer>().Instance; if (editManager != null) { editManager.Undo(); } } if (redo) { redo = false; var editManager = GetComponent <VoxelEditManagerContainer>().Instance; if (editManager != null) { editManager.Redo(); } } if (!lockSelection) { Camera camera = Camera.current; if (camera != null) { Vector3 relPos = camera.transform.position - transform.position; Vector3 relDir = Quaternion.Inverse(transform.rotation) * camera.transform.forward.normalized; //if (field.RayCast(relPos, relDir, 16, out TestVoxelField.RayCastResult result)) if (gameObject.GetComponent <VoxelWorldContainer>().Instance.RayCast(relPos, relDir, 64, out VoxelWorld <MortonIndexer> .RayCastResult result)) { selectedCell = new Vector3Int(Mathf.FloorToInt(result.pos.x), Mathf.FloorToInt(result.pos.y), Mathf.FloorToInt(result.pos.z)); } else { selectedCell = null; } if (selectedCell != null) { lockedSelection = selectedCell.Value; } else { lockedSelection = Vector3Int.zero; } } else { selectedCell = null; } } else { selectedCell = lockedSelection; } if (selectedCell != null && prevSelectedCell != selectedCell) { //field.FillCell(selectedCell.Value.x, selectedCell.Value.y, selectedCell.Value.z, 0, gizmoCellMaterials, gizmoCellIntersections, gizmoCellNormals); var sculpture = gameObject.GetComponent <VoxelWorldContainer>().Instance; VoxelChunk <MortonIndexer> chunk = sculpture.GetChunk(ChunkPos.FromVoxel(selectedCell.Value, sculpture.ChunkSize)); if (chunk != null) { chunk.FillCell( ((selectedCell.Value.x % sculpture.ChunkSize) + sculpture.ChunkSize) % sculpture.ChunkSize, ((selectedCell.Value.y % sculpture.ChunkSize) + sculpture.ChunkSize) % sculpture.ChunkSize, ((selectedCell.Value.z % sculpture.ChunkSize) + sculpture.ChunkSize) % sculpture.ChunkSize, 0, gizmoCellMaterials, gizmoCellIntersections, gizmoCellNormals); gizmoCell = new RawArrayVoxelCell(0, (Vector3)selectedCell.Value, gizmoCellMaterials, gizmoCellIntersections, gizmoCellNormals); NativeMemoryCache memoryCache = new NativeMemoryCache(Allocator.Persistent); var polygonizer = new CMSVoxelPolygonizer <RawArrayVoxelCell, CMSStandardProperties, SvdQefSolver <RawArrayVoxelCell>, IntersectionSharpFeatureSolver <RawArrayVoxelCell> >(new CMSStandardProperties(), new SvdQefSolver <RawArrayVoxelCell>(), new IntersectionSharpFeatureSolver <RawArrayVoxelCell>(), memoryCache); var components = new NativeList <VoxelMeshComponent>(Allocator.Persistent); var componentIndices = new NativeList <PackedIndex>(Allocator.Persistent); var componentVertices = new NativeList <VoxelMeshComponentVertex>(Allocator.Persistent); polygonizer.Polygonize(gizmoCell, components, componentIndices, componentVertices); gizmoComponents = new List <VoxelMeshComponent>(components.Length); for (int i = 0; i < components.Length; i++) { gizmoComponents.Add(components[i]); } gizmoComponentIndices = new List <PackedIndex>(componentIndices.Length); for (int i = 0; i < componentIndices.Length; i++) { gizmoComponentIndices.Add(componentIndices[i]); } gizmoComponentVertices = new List <VoxelMeshComponentVertex>(componentVertices.Length); for (int i = 0; i < componentVertices.Length; i++) { gizmoComponentVertices.Add(componentVertices[i]); } memoryCache.Dispose(); components.Dispose(); componentIndices.Dispose(); componentVertices.Dispose(); gizmoPosition = selectedCell.Value; gizmoTransform = Matrix4x4.TRS(transform.position, transform.rotation, transform.lossyScale); } } prevSelectedCell = selectedCell; float brushSize = 2.1f + 8; if (placeSdf) { placeSdf = false; regenerate = true; var editManager = GetComponent <VoxelEditManagerContainer>().Instance; switch (brushType) { case BrushType.Sphere: gameObject.GetComponent <VoxelWorldContainer>().Instance.ApplySdf(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new SphereSDF(brushSize), MaterialColors.ToInteger(materialRed, materialGreen, materialBlue, materialTexture), replaceSdfMaterial, editManager.Consumer()); break; case BrushType.Box: gameObject.GetComponent <VoxelWorldContainer>().Instance.ApplySdf(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new BoxSDF(brushSize), MaterialColors.ToInteger(materialRed, materialGreen, materialBlue, materialTexture), replaceSdfMaterial, editManager.Consumer()); break; case BrushType.Cylinder: gameObject.GetComponent <VoxelWorldContainer>().Instance.ApplySdf(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new CylinderSDF(brushSize, brushSize), MaterialColors.ToInteger(materialRed, materialGreen, materialBlue, materialTexture), replaceSdfMaterial, editManager.Consumer()); break; case BrushType.Pyramid: gameObject.GetComponent <VoxelWorldContainer>().Instance.ApplySdf(new Vector3(gizmoPosition.x, gizmoPosition.y - brushSize / 2, gizmoPosition.z), Quaternion.Euler(sdfRotation), new PyramidSDF(brushSize * 2, brushSize * 2), MaterialColors.ToInteger(materialRed, materialGreen, materialBlue, materialTexture), replaceSdfMaterial, editManager.Consumer()); break; case BrushType.Mesh: var mesh = voxelizeMesh.mesh; var triangles = mesh.triangles; var vertices = mesh.vertices; var normals = mesh.normals; var inVertices = new NativeArray <float3>(triangles.Length, Allocator.TempJob); var inNormals = new NativeArray <float3>(triangles.Length, Allocator.TempJob); for (int l = triangles.Length, i = 0; i < l; i += 3) { inVertices[i] = vertices[triangles[i]]; inVertices[i + 1] = vertices[triangles[i + 1]]; inVertices[i + 2] = vertices[triangles[i + 2]]; inNormals[i] = normals[triangles[i]]; inNormals[i + 1] = normals[triangles[i + 1]]; inNormals[i + 2] = normals[triangles[i + 2]]; } int voxelizerSize = 64; var outVoxels = new NativeArray3D <Voxel.Voxel, MortonIndexer>(new MortonIndexer(voxelizerSize, voxelizerSize, voxelizerSize), voxelizerSize, voxelizerSize, voxelizerSize, Allocator.TempJob); var voxelizationProperties = smoothVoxelizerNormals ? Voxelizer.VoxelizationProperties.SMOOTH : Voxelizer.VoxelizationProperties.FLAT; var watch = new System.Diagnostics.Stopwatch(); watch.Start(); using (var job = Voxelizer.Voxelize(inVertices, inNormals, outVoxels, MaterialColors.ToInteger(materialRed, materialGreen, materialBlue, materialTexture), voxelizationProperties)) { job.Handle.Complete(); } watch.Stop(); Debug.Log("Voxelized mesh: " + watch.ElapsedMilliseconds + "ms"); watch.Reset(); watch.Start(); //TODO Make voxelizer also undoable? gameObject.GetComponent <VoxelWorldContainer>().Instance.ApplyGrid((int)gizmoPosition.x, (int)gizmoPosition.y, (int)gizmoPosition.z, outVoxels, true, false, null); watch.Stop(); Debug.Log("Applied to grid: " + watch.ElapsedMilliseconds + "ms"); inVertices.Dispose(); inNormals.Dispose(); outVoxels.Dispose(); break; case BrushType.Custom: using (var sdf = customBrush.Instance.CreateSdf(Allocator.TempJob)) { gameObject.GetComponent <VoxelWorldContainer>().Instance.ApplySdf(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), sdf, MaterialColors.ToInteger(materialRed, materialGreen, materialBlue, materialTexture), replaceSdfMaterial, editManager.Consumer()); } break; } } if (gizmoPosition != null) { switch (brushType) { case BrushType.Sphere: gameObject.GetComponent <SdfShapeRenderHandler>().Render(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new SphereSDF(brushSize)); break; case BrushType.Box: gameObject.GetComponent <SdfShapeRenderHandler>().Render(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new BoxSDF(brushSize)); break; case BrushType.Cylinder: gameObject.GetComponent <SdfShapeRenderHandler>().Render(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new CylinderSDF(brushSize, brushSize)); break; case BrushType.Pyramid: gameObject.GetComponent <SdfShapeRenderHandler>().Render(new Vector3(gizmoPosition.x, gizmoPosition.y - brushSize / 2, gizmoPosition.z), Quaternion.Euler(sdfRotation), new PyramidSDF(brushSize * 2, brushSize * 2)); break; case BrushType.Custom: Matrix4x4 brushTransform = Matrix4x4.TRS(new Vector3(gizmoPosition.x, gizmoPosition.y, gizmoPosition.z), Quaternion.Euler(sdfRotation), new Vector3(1, 1, 1)); using (var sdf = customBrush.Instance.CreateSdf(Allocator.TempJob)) { gameObject.GetComponent <SdfShapeRenderHandler>().Render(brushTransform, sdf); } Camera camera = Camera.current; if (camera != null) { selectedPrimitive = -1; var ray = camera.transform.forward.normalized; float maxDst = 60.0f; int steps = Mathf.CeilToInt(maxDst * 2); for (int i = 0; i < steps && selectedPrimitive < 0; i++) { var pos = camera.transform.position + ray * maxDst / steps * i; int j = 0; foreach (var primitive in customBrush.Instance.Primitives) { var renderSdf = customBrush.Instance.Evaluator.GetRenderSdf(primitive); if (renderSdf != null && renderSdf.Eval(math.mul(math.mul(brushTransform, primitive.invTransform), new float4(pos, 1.0f)).xyz) < 0) { selectedPrimitive = j; break; } j++; } } } if (selectedPrimitive >= 0 && selectedPrimitive < customBrush.Instance.Primitives.Count) { var primitive = customBrush.Instance.Primitives[selectedPrimitive]; var renderSdf = customBrush.Instance.Evaluator.GetRenderSdf(primitive); if (renderSdf != null) { gameObject.GetComponent <SdfShapeRenderHandler>().Render(brushTransform * (Matrix4x4)primitive.transform, renderSdf); } } break; } } if (generateEachFrame || regenerate) { regenerate = false; //GenerateMesh(); } }