/** * Create surface for overlay */ public ArrayMesh createSurfaceOverlay(ArrayMesh mesh, string slotName, string urlPath, string overlayName, List <UMAReciepeBindPose> origBindPoses) { var file = ResourceLoader.Load <PackedScene>(urlPath); var instance = file.Instance(); var meshes = new List <MeshInstance>(); if (instance is Spatial) { foreach (var child in (instance as Spatial).GetChildren()) { if (child is MeshInstance) { meshes.Add(child as MeshInstance); } } } if (instance is MeshInstance) { meshes.Add(instance as MeshInstance); } var mdt = new MeshDataTool(); var idx = mesh.SurfaceFindByName(slotName); mdt.CreateFromSurface(mesh, idx); int totalSurfaces = 0; foreach (var mi in meshes) { var newMesh = (mi as MeshInstance).Mesh; var newSkin = (mi as MeshInstance).Skin; for (int surface = 0; surface < newMesh.GetSurfaceCount(); surface++) { mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, createSurfaceByBones(newMesh as ArrayMesh, surface, newSkin, origBindPoses)); var lastId = mesh.GetSurfaceCount() - 1; var mat = newMesh.SurfaceGetMaterial(surface); mat.ResourceLocalToScene = true; if (mat is SpatialMaterial) { (mat as SpatialMaterial).ParamsGrow = true; (mat as SpatialMaterial).ParamsGrowAmount = 0.005f; } mesh.SurfaceSetMaterial(lastId, mat); mesh.SurfaceSetName(lastId, (totalSurfaces == 0) ? overlayName : overlayName + "/" + totalSurfaces); totalSurfaces++; } changes++; } return(mesh); }
public override UnifiedObject Mirror() { StaticObject clone = (StaticObject)this.Clone(); ArrayMesh originalMesh = (ArrayMesh)this.m_meshInstance.Mesh; int originalSurfaceCount = originalMesh.GetSurfaceCount(); ArrayMesh newMesh = new ArrayMesh(); for (int i = 0; i < originalSurfaceCount; i++) { MeshDataTool mdt = new MeshDataTool(); mdt.CreateFromSurface(originalMesh, i); for (int j = 0; j < mdt.GetVertexCount(); j++) { Vector3 vert = mdt.GetVertex(j); vert.x *= -1; mdt.SetVertex(j, vert); } mdt.CommitToSurface(newMesh); } clone.ObjectMeshInstance.Mesh = newMesh; return(clone); }
/** * Clean up old surfacess **/ private ArrayMesh cleanOldSlots(ArrayMesh oldMesh, UMAReciepe reciepe) { List <string> oldSurfaces = new List <string>(); for (int surface = 0; surface < oldMesh.GetSurfaceCount(); surface++) { oldSurfaces.Add(oldMesh.SurfaceGetName(surface)); } var allSlotNames = reciepe.slots.Select(tf => tf.Key).ToList(); //clean up current surface by new slots foreach (var oldSurface in oldSurfaces) { bool exist = false; foreach (var reicpeSlotName in allSlotNames) { if (oldSurface.Contains(reicpeSlotName)) { exist = true; } } if (!exist) { Console.WriteLine("[UMA] Delete surface " + oldSurface); oldMesh.SurfaceRemove(oldMesh.SurfaceFindByName(oldSurface)); changes++; } } return(oldMesh); }
public static ArrayMesh AddNoiseToMesh(PlaneMesh plane, float[,] noiseMap, int chunkSize, int heightMultiplier, Curve heightCurve) { SurfaceTool st = new SurfaceTool(); st.CreateFrom(plane, 0); ArrayMesh mesh = new ArrayMesh(); MeshDataTool dt = new MeshDataTool(); mesh = st.Commit(); dt.CreateFromSurface(mesh, 0); for (int y = 0; y < chunkSize; y++) { for (int x = 0; x < chunkSize; x++) { int z = y; int vertexIndex = z * chunkSize + x; Vector3 vertex = dt.GetVertex(vertexIndex); vertex.y = heightCurve.Interpolate(noiseMap[chunkSize - x - 1, chunkSize - z - 1]) * heightMultiplier; dt.SetVertex(vertexIndex, vertex); } } for (int surface = 0; surface < mesh.GetSurfaceCount(); surface++) { mesh.SurfaceRemove(surface); } dt.CommitToSurface(mesh); st.Begin(Mesh.PrimitiveType.Triangles); st.CreateFrom(mesh, 0); st.Index(); st.GenerateNormals(); return(st.Commit()); }
/** * create overlay */ private ArrayMesh createOverlays(ArrayMesh oldMesh, UMAReciepe reciepe) { Dictionary <int, string> oldSurfaces = new Dictionary <int, string>(); for (int surface = 0; surface < oldMesh.GetSurfaceCount(); surface++) { var name = oldMesh.SurfaceGetName(surface); oldSurfaces.Add(surface, name); } foreach (var slot in reciepe.slots) { var slotName = slot.Key; var path = System.IO.Path.Combine(reciepe.slotPath, slot.Key + ".tscn"); var restBones = extractBinds(path); foreach (var overlay in slot.Value) { var overlayName = slotName + "/Overlay_" + overlay.Key; if (!oldSurfaces.ContainsValue(overlayName)) { var overlayPath = System.IO.Path.Combine(overlay.Value.overlayPath, overlay.Key + ".tscn"); oldMesh = createSurfaceOverlay(oldMesh, slotName, overlayPath, overlayName, restBones); } } } return(oldMesh); }
// Called when the node enters the scene tree for the first time. public override void _Ready() { StreamReader textReader = new StreamReader(@"./UMA/Content/UMA_Core/HumanMale/Slots/Body/UMA_Human_Male_Legs_Slot.asset"); textReader.ReadLine(); textReader.ReadLine(); textReader.ReadLine(); var deserializer = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); var slotData = deserializer.Deserialize <SlotYaml>(textReader); GD.Print(slotData.MonoBehaviour.MName); var verticeOrder = decodeUnitysCompressionSubMesh(slotData.MonoBehaviour.MeshData.Submeshes[0].Triangles); var surfaceArray = new Godot.Collections.Array(); surfaceArray.Resize(ARRAY_MAX); surfaceArray[ARRAY_VERTEX] = slotData.MonoBehaviour.MeshData.Vertices; surfaceArray[ARRAY_NORMAL] = slotData.MonoBehaviour.MeshData.Normals; surfaceArray[ARRAY_TANGENTS] = CreateTangents(slotData.MonoBehaviour.MeshData.Tangents); surfaceArray[ARRAY_TEX_UV] = slotData.MonoBehaviour.MeshData.Uv; surfaceArray[ARRAY_INDEX] = verticeOrder; ArrayMesh legMesh = new ArrayMesh(); legMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfaceArray, null, ARRAY_FORMAT_VERTEX + ARRAY_FORMAT_NORMAL + ARRAY_FORMAT_TANGENT + ARRAY_FORMAT_TANGENT); var legMaterial = (SpatialMaterial)GD.Load("res://skin.material"); GD.Print("Surface Count" + legMesh.GetSurfaceCount()); var node = (MeshInstance)FindNode("UmaMeshNode"); GD.Print(node.GetType()); GD.Print(node.Mesh.ToString()); legMesh.SurfaceSetMaterial(0, legMaterial); node.SetMesh(legMesh); GD.Print(node.Mesh.ToString()); /* * DynamicCharacterAvatar characterAvatar= new DynamicCharacterAvatar(); * * DynamicAssetLoader.Instance = new DynamicAssetLoader(); * * UMA.UMAContext.Instance = new UMA.UMAContext(); * characterAvatar.context = UMA.UMAContext.Instance; * UMA.UMAContext.Instance.raceLibrary = new DynamicRaceLibrary(); * * UMATextRecipe textRecipe = new UMATextRecipe(); * textRecipe.recipeString = @"{""version"":3,""packedSlotDataList"":[],""slotsV2"":[],""slotsV3"":[{""id"":""MaleEyes"",""scale"":100,""copyIdx"":-1,""overlays"":[{""id"":""EyeOverlay"",""colorIdx"":3,""rect"":[0,0,0,0]},{""id"":""Default Eye Adjust"",""colorIdx"":2,""rect"":[0,0,0,0]}]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":""MaleInnerMouth"",""scale"":100,""copyIdx"":-1,""overlays"":[{""id"":""InnerMouth"",""colorIdx"":4,""rect"":[0,0,0,0]}]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":""MaleTorso"",""scale"":100,""copyIdx"":-1,""overlays"":[{""id"":""M_BodOverlay 1"",""colorIdx"":0,""rect"":[0,0,0,0]}]},{""id"":""MaleFeet"",""scale"":100,""copyIdx"":16,""overlays"":[]},{""id"":""MaleHands"",""scale"":100,""copyIdx"":16,""overlays"":[]},{""id"":""MaleLegs"",""scale"":100,""copyIdx"":16,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":"""",""scale"":1,""copyIdx"":-1,""overlays"":[]},{""id"":""M_Highpoly Head"",""scale"":100,""copyIdx"":-1,""overlays"":[{""id"":""M_Face"",""colorIdx"":0,""rect"":[0,0,0,0]}]}],""colors"":[],""fColors"":[{""name"":""Skin"",""colors"":[255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0]},{""name"":""Hair"",""colors"":[255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0]},{""name"":""Eyes"",""colors"":[255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0]},{""name"":""-"",""colors"":[255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0]},{""name"":""-"",""colors"":[234,234,234,255,0,0,0,0,255,255,255,255,0,0,0,0,255,255,255,255,0,0,0,0]}],""sharedColorCount"":3,""race"":""HumanMale"",""packedDna"":[{""dnaType"":""DynamicUMADna"",""dnaTypeHash"":815443803,""packedDna"":""{\""bDnaAsset\"":{\""instanceID\"":12024},\""bDnaAssetName\"":\""HumanMaleDynamicDnaAsset\"",\""bDnaSettings\"":[{\""name\"":\""skinGreenness\"",\""value\"":128},{\""name\"":\""skinBlueness\"",\""value\"":128},{\""name\"":\""skinRedness\"",\""value\"":128},{\""name\"":\""height\"",\""value\"":128},{\""name\"":\""headSize\"",\""value\"":128},{\""name\"":\""headWidth\"",\""value\"":128},{\""name\"":\""neckThickness\"",\""value\"":128},{\""name\"":\""armLength\"",\""value\"":128},{\""name\"":\""forearmLength\"",\""value\"":128},{\""name\"":\""armWidth\"",\""value\"":128},{\""name\"":\""forearmWidth\"",\""value\"":128},{\""name\"":\""handsSize\"",\""value\"":128},{\""name\"":\""feetSize\"",\""value\"":128},{\""name\"":\""legSeparation\"",\""value\"":128},{\""name\"":\""upperMuscle\"",\""value\"":128},{\""name\"":\""lowerMuscle\"",\""value\"":128},{\""name\"":\""upperWeight\"",\""value\"":128},{\""name\"":\""lowerWeight\"",\""value\"":128},{\""name\"":\""legsSize\"",\""value\"":128},{\""name\"":\""belly\"",\""value\"":128},{\""name\"":\""waist\"",\""value\"":128},{\""name\"":\""gluteusSize\"",\""value\"":128},{\""name\"":\""earsSize\"",\""value\"":128},{\""name\"":\""earsPosition\"",\""value\"":128},{\""name\"":\""earsRotation\"",\""value\"":128},{\""name\"":\""noseSize\"",\""value\"":128},{\""name\"":\""noseCurve\"",\""value\"":128},{\""name\"":\""noseWidth\"",\""value\"":128},{\""name\"":\""noseInclination\"",\""value\"":128},{\""name\"":\""nosePosition\"",\""value\"":128},{\""name\"":\""nosePronounced\"",\""value\"":128},{\""name\"":\""noseFlatten\"",\""value\"":128},{\""name\"":\""chinSize\"",\""value\"":128},{\""name\"":\""chinPronounced\"",\""value\"":128},{\""name\"":\""chinPosition\"",\""value\"":128},{\""name\"":\""mandibleSize\"",\""value\"":128},{\""name\"":\""jawsSize\"",\""value\"":128},{\""name\"":\""jawsPosition\"",\""value\"":128},{\""name\"":\""cheekSize\"",\""value\"":128},{\""name\"":\""cheekPosition\"",\""value\"":128},{\""name\"":\""lowCheekPronounced\"",\""value\"":128},{\""name\"":\""lowCheekPosition\"",\""value\"":128},{\""name\"":\""foreheadSize\"",\""value\"":128},{\""name\"":\""foreheadPosition\"",\""value\"":128},{\""name\"":\""lipsSize\"",\""value\"":128},{\""name\"":\""mouthSize\"",\""value\"":128},{\""name\"":\""eyeRotation\"",\""value\"":128},{\""name\"":\""eyeSize\"",\""value\"":128},{\""name\"":\""breastSize\"",\""value\"":128},{\""name\"":\""eyeSpacing\"",\""value\"":128}]}""}],""wardrobeSet"":[],""packedRecipeType"":""Standard""}"; * GD.Print(textRecipe.recipeString); * characterAvatar.umaRecipe = textRecipe; * * UMAGenerator generator = new UMAGenerator(); * characterAvatar.umaGenerator = generator; * * characterAvatar.Start(); * GD.Print("It actually made it to the end of the Start routine!");*/ }
void apply_color(ArrayMesh am) { int surface_count = am.GetSurfaceCount(); SpatialMaterial[] mats = make_materials(surface_count); for (int i = 0; i < surface_count; i++) { am.SurfaceSetMaterial(i, mats[i]); } }
public void Generate() { planeMesh = new PlaneMesh(); planeMesh.Size = new Vector2(chunkSize, chunkSize); planeMesh.SubdivideDepth = Mathf.RoundToInt(chunkSize * 0.5f); planeMesh.SubdivideWidth = Mathf.RoundToInt(chunkSize * 0.5f); surfaceTool = new SurfaceTool(); meshDataTool = new MeshDataTool(); surfaceTool.CreateFrom(planeMesh, 0); arrayPlane = surfaceTool.Commit(); meshDataTool.CreateFromSurface(arrayPlane, 0); for (int i = 0; i < meshDataTool.GetVertexCount(); i++) { Vector3 vertex = meshDataTool.GetVertex(i); vertex.y = noise.GetNoise3d( vertex.x + position.x, vertex.y, vertex.z + position.z) * References.steepness; meshDataTool.SetVertex(i, vertex); avgHeight += vertex.y; } avgHeight /= meshDataTool.GetVertexCount(); for (int i = 0; i < arrayPlane.GetSurfaceCount(); i++) { arrayPlane.SurfaceRemove(i); } for (int i = 0; i < meshDataTool.GetFaceCount(); i++) { Vector3 A = meshDataTool.GetVertex(meshDataTool.GetFaceVertex(i, 0)); Vector3 B = meshDataTool.GetVertex(meshDataTool.GetFaceVertex(i, 1)); Vector3 C = meshDataTool.GetVertex(meshDataTool.GetFaceVertex(i, 2)); Vector3 face = (A + B + C) / 3 + position; Vector3 normal = meshDataTool.GetFaceNormal(i); slope += Maths.Angle(Vector3.Up, normal); } slope /= meshDataTool.GetFaceCount(); meshDataTool.CommitToSurface(arrayPlane); surfaceTool.Begin(Mesh.PrimitiveType.Triangles); surfaceTool.CreateFrom(arrayPlane, 0); surfaceTool.GenerateNormals(); meshInstance = new MeshInstance(); meshInstance.Mesh = surfaceTool.Commit(); meshInstance.SetSurfaceMaterial(0, (Material)ResourceLoader.Load("res://Assets/Shader/Terrain.material")); meshInstance.CreateTrimeshCollision(); meshInstance.CastShadow = GeometryInstance.ShadowCastingSetting.On; AddChild(meshInstance); }
public static IEnumerable <IMeshSurface> GetSurfaces(this ArrayMesh mesh) { Ensure.That(mesh, nameof(mesh)).IsNotNull(); var count = mesh.GetSurfaceCount(); for (var i = 0; i < count; i++) { yield return(new ArrayMeshSurface(mesh, i)); } }
// Apply the default material on each surface private static void ApplyMaterial(ArrayMesh mesh) { if (DefaultMaterial is null) { DefaultMaterial = (SpatialMaterial)ResourceLoader.Load(DefaultMaterialPath); } // Apply the material on each surface for (int i = 0; i < mesh.GetSurfaceCount(); i++) { mesh.SurfaceSetMaterial(i, DefaultMaterial); } }
protected void assignMaterialOverlay(ArrayMesh oldMesh, string overlayName, bool useAlbedo, Color albedoColor, string materialPath, float glow) { if (oldMesh == null) { return; } for (int surface = 0; surface < oldMesh.GetSurfaceCount(); surface++) { var name = oldMesh.SurfaceGetName(surface); if (!name.Contains(overlayName)) { continue; } var material = oldMesh.SurfaceGetMaterial(surface); if (!String.IsNullOrEmpty(materialPath)) { //fix path combine (system.io) materialPath = materialPath.Replace(@"\", @"/"); if ((material == null) || (material.ResourcePath != materialPath)) { var newMaterial = GD.Load <Material>(materialPath); if (newMaterial is SpatialMaterial) { (newMaterial as SpatialMaterial).ParamsGrow = true; (newMaterial as SpatialMaterial).ParamsGrowAmount = glow; } newMaterial.ResourceLocalToScene = true; material = newMaterial; } } if (material != null) { if (useAlbedo) { (material as SpatialMaterial).AlbedoColor = albedoColor; } (material as SpatialMaterial).ParamsGrow = true; (material as SpatialMaterial).ParamsGrowAmount = glow; oldMesh.SurfaceSetMaterial(surface, material); } } }
/// <summary> /// Fills the <paramref name="mesh"/> with the data in the draft /// </summary> /// <param name="mesh"> Resulting mesh. Cleared before use. </param> /// <param name="calculateBounds"> Calculate the bounding box of the Mesh after setting the triangles. </param> /// <param name="autoIndexFormat"> Use 16 bit or 32 bit index buffers based on vertex count. </param> public void ToMesh(ref ArrayMesh mesh, bool calculateBounds = true, bool autoIndexFormat = true) { if (mesh == null) { throw new ArgumentNullException("mesh"); } var surfaceCount = mesh.GetSurfaceCount(); for (int i = 0; i < surfaceCount; i++) { mesh.SurfaceRemove(0); } mesh.ClearBlendShapes(); FillMesh(ref mesh, calculateBounds, autoIndexFormat); }
/** * Create surface overlay */ public ArrayMesh createSurface(ArrayMesh mesh, string urlPath, string overlayName) { var file = ResourceLoader.Load <PackedScene>(urlPath); var instance = file.Instance(); var meshes = new List <MeshInstance>(); if (instance is Spatial) { foreach (var child in (instance as Spatial).GetChildren()) { if (child is MeshInstance) { meshes.Add(child as MeshInstance); } } } if (instance is MeshInstance) { meshes.Add(instance as MeshInstance); } int totalSurfaces = 0; foreach (var mi in meshes) { var newMesh = (mi as MeshInstance).Mesh; for (int surface = 0; surface < newMesh.GetSurfaceCount(); surface++) { mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, newMesh.SurfaceGetArrays(surface)); var lastId = mesh.GetSurfaceCount() - 1; var mat = newMesh.SurfaceGetMaterial(surface); mat.ResourceLocalToScene = true; mesh.SurfaceSetMaterial(lastId, mat); mesh.SurfaceSetName(lastId, (totalSurfaces == 0) ? overlayName : overlayName + "/" + totalSurfaces); totalSurfaces++; } changes++; } return(mesh); }
private ArrayMesh cleanOldOverlays(ArrayMesh oldMesh, UMAReciepe reciepe) { List <string> oldSurfaces = new List <string>(); for (int surface = 0; surface < oldMesh.GetSurfaceCount(); surface++) { oldSurfaces.Add(oldMesh.SurfaceGetName(surface)); } foreach (var oldSurface in oldSurfaces) { bool exist = false; if (!oldSurface.Contains("Overlay_")) { continue; } foreach (var slot in reciepe.slots) { var slotName = slot.Key; foreach (var overlay in slot.Value) { var overlayName = slotName + "/Overlay_" + overlay.Key; if (oldSurface.Contains(overlayName)) { exist = true; } } } if (!exist) { Console.WriteLine("[UMA] Delete overlay " + oldSurface); oldMesh.SurfaceRemove(oldMesh.SurfaceFindByName(oldSurface)); changes++; } } return(oldMesh); }
public static void CopyTo(this IMeshSurface surface, ArrayMesh target) { Ensure.That(surface, nameof(surface)).IsNotNull(); Ensure.That(surface, nameof(surface)).IsNotNull(); var index = target.SurfaceFindByName(surface.Key); if (index != -1) { target.SurfaceRemove(index); } var existingShapes = target.GetBlendShapeNames().ToHashSet(); surface.BlendShapes.Map(b => b.Key).Filter(k => !existingShapes.Contains(k)).Iter(target.AddBlendShape); target.BlendShapeMode = surface.BlendShapeMode; var newIndex = target.GetSurfaceCount(); Array CopyBlendShape(IMeshData <MorphableVertex> source) { var shape = new Array(); source.Export() .Cast <object>() .Map((i, a) => i == (int)ArrayMesh.ArrayType.Index ? null : a) .Iter(a => shape.Add(a)); return(shape); } var data = surface.Data.Export(); var shapes = new Array(surface.BlendShapes.Map(CopyBlendShape)); target.AddSurfaceFromArrays(surface.PrimitiveType, data, shapes); target.SurfaceSetName(newIndex, surface.Key); surface.Material.Iter(m => target.SurfaceSetMaterial(newIndex, m)); }
/** * create slots */ private ArrayMesh createNewSlots(ArrayMesh oldMesh, UMAReciepe reciepe) { Dictionary <int, string> oldSurfaces = new Dictionary <int, string>(); for (int surface = 0; surface < oldMesh.GetSurfaceCount(); surface++) { var name = oldMesh.SurfaceGetName(surface); oldSurfaces.Add(surface, name); } foreach (var slot in reciepe.slots) { if (!oldSurfaces.ContainsValue(slot.Key)) { var path = System.IO.Path.Combine(reciepe.slotPath, slot.Key + ".tscn"); //create slot Console.WriteLine("[UMA] Create slot: " + path); oldMesh = createSurface(oldMesh, path, slot.Key); } } return(oldMesh); }
/// <summary> /// Creates the actual mesh object. Call InitializeMesh instead of this directly /// </summary> private void BuildMesh() { // This is actually a triangle list, but the index buffer is used to build // the indices (to emulate a triangle fan) var bufferSize = vertices2D.Count + 2; var indexSize = vertices2D.Count * 3; var arrays = new Godot.Collections.Array(); arrays.Resize((int)Mesh.ArrayType.Max); // Build vertex, index, and uv lists // Index mapping to build all triangles var indices = new int[indexSize]; int currentVertexIndex = 1; for (int i = 0; i < indexSize; i += 3) { indices[i] = 0; indices[i + 1] = currentVertexIndex + 1; indices[i + 2] = currentVertexIndex; ++currentVertexIndex; } // Write mesh data // var vertices = new Vector3[bufferSize]; var uvs = new Vector2[bufferSize]; int writeIndex = 0; writeIndex = InitializeCorrectMembrane(writeIndex, vertices, uvs); if (writeIndex != bufferSize) { throw new Exception("Membrane buffer write ended up at wrong index"); } // Godot might do this automatically // // Set the bounds to get frustum culling and LOD to work correctly. // // TODO: make this more accurate by calculating the actual extents // m_mesh->_setBounds(Ogre::Aabb(Float3::ZERO, Float3::UNIT_SCALE * 50) // /*, false*/); // m_mesh->_setBoundingSphereRadius(50); arrays[(int)Mesh.ArrayType.Vertex] = vertices; arrays[(int)Mesh.ArrayType.Index] = indices; arrays[(int)Mesh.ArrayType.TexUv] = uvs; // Create the mesh var generatedMesh = new ArrayMesh(); var surfaceIndex = generatedMesh.GetSurfaceCount(); generatedMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays); // Apply the mesh to us Mesh = generatedMesh; SetSurfaceMaterial(surfaceIndex, MaterialToEdit); }
public async void UpdateShapes() { // await System.Threading.Thread.SpinWait(1000); await System.Threading.Tasks.Task.Delay(100); try { using (var frames = pipe.WaitForFrames()) using (var depth = frames.DepthFrame) using (var points = pc.Process(depth).As <Points>()) { // CopyVertices is extensible, any of these will do: float[] vertices; vertices = new float[points.Count * 3]; points.CopyVertices(vertices); Points = vertices; } // Remove all children from the detectbody foreach (Node child in detectBody.GetChildren()) { child.QueueFree(); } if (detectBody.GetShapeOwners().Count > 0) { GD.Print(detectBody.GetShapeOwners().Count); for (int l = 0; l < detectBody.GetShapeOwners().Count; l++) { detectBody.ShapeOwnerClearShapes((uint)l); } } } catch { } detectedPoints.Clear(); sortedPoints.Clear(); Vector3 currentGroundPoint = new Vector3(); // allPoints = new Vector3[101760]; for (int i = 0; i < meshDataTool.GetVertexCount(); i++) // 101760 { Vector3 vertex = meshDataTool.GetVertex(i); int indexOfX = i * 3; int indexOfY = i * 3 + 1; int indexOfZ = i * 3 + 2; float x = Points[indexOfX]; float y = Points[indexOfY]; float z = Points[indexOfZ]; bool shapeFoundForPoint = false; // GD.Print(x); if (z > distanceToGround || z == 0.0f || z < 0 || x < syncPointTL.x || y > syncPointTL.y || x > syncPointBR.x || y < syncPointBR.y) { z = 0; } else { z = (distanceToGround - z) * 2; if (vertex.y > 0) { currentGroundPoint = vertex; currentGroundPoint.y = 0; //------------------------------------------------- For each point test -------------------------------------------------- if (detectedPoints.Count == 0) { // make a vector on the ground for the detection shape to get a height List <Vector3> shapePoints = new List <Vector3> { currentGroundPoint, vertex }; detectedPoints.Add(shapePoints); // Add the vectors to a list with shapes } else { for (int j = 0; j < detectedPoints.Count; j++) // Run thrugh all the shapes { int lengthOfShape = detectedPoints[j].Count; // number of points in shape // find the shape with a last added start point... if (detectedPoints[j][lengthOfShape - 2].DistanceTo(currentGroundPoint) < 1) //4 distanceBetweenPoints { detectedPoints[j].Add(currentGroundPoint); detectedPoints[j].Add(vertex); shapeFoundForPoint = true; break; } } if (shapeFoundForPoint == false) { //... create a new shape and add the points List <Vector3> shapePoints = new List <Vector3> { currentGroundPoint, vertex }; detectedPoints.Add(shapePoints); } } shapeFoundForPoint = false; //------------------------------------------------------------------------------------------------------------------------ } } vertex.y = z; meshDataTool.SetVertex(i, vertex); // Draw shape } Vector3 prevPoint = new Vector3(10, 10, 10); Vector3 prevprevPoint = new Vector3(10, 10, 10); // ---------------------------- Add points to shapes -------------------------- for (int i = 0; i < detectedPoints.Count; i++) { // Point (000) removal detectedPoints[i].RemoveAll(item => item == pointZero); for (int j = 0; j < detectedPoints[i].Count; j++) { if (detectedPoints[i][j].z != prevprevPoint.z) { prevprevPoint = prevPoint; prevPoint = detectedPoints[i][j]; } else if (detectedPoints[i][j].z == prevprevPoint.z) { prevprevPoint = prevPoint; prevPoint = detectedPoints[i][j]; detectedPoints[i].Remove(prevprevPoint); } } int pointSets = 100000; var sortOut = detectedPoints[i].Where((x, n) => n % pointSets == 0 || n - 1 % pointSets == 0); Vector3[] convertedArr = sortOut.ToArray(); // -------------------------- Must be turned on ---------------------- convexPolygonShape = new ConvexPolygonShape(); convexPolygonShape.Points = convertedArr; var areaShape = new Area(); areaShape.AddToGroup("cameraDetections"); DetectionCollisionShape = new CollisionShape(); DetectionCollisionShape.Shape = convexPolygonShape; DetectionCollisionShape.Shape.Margin = 1; areaShape.AddChild(DetectionCollisionShape); detectBody.AddChild(areaShape); // ---------------------------------------------------------------- } detectedPoints.Clear(); sortedPoints.Clear(); // ---------------------------- Remove surface -------------------------- for (int j = 0; j < arrayPlane.GetSurfaceCount(); j++) { arrayPlane.SurfaceRemove(j); // Removes the drawing } meshDataTool.CommitToSurface(arrayPlane); // Resets the surface UpdateShapes(); // Rerun function }