public void RemoveObject(string ObjName) { //get the main mmf table and remove the key MemoryMappedFile map = new MemoryMappedFile(); if (map.OpenEx(ObjectNamesMMF + ".nat", MapProtection.PageReadWrite, ObjectNamesMMF, MapAccess.FileMapAllAccess)) { BinaryFormatter bf = new BinaryFormatter(); MapViewStream mmfStream = map.MapView(MapAccess.FileMapRead, 0, 0, ""); mmfStream.Position = 0; Hashtable oFilesMap = bf.Deserialize(mmfStream) as Hashtable; oFilesMap.Remove(ObjName); mmfStream.Close(); //update the main file bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, oFilesMap); MapViewStream stream = map.MapView(MapAccess.FileMapAllAccess, 0, (int)0, ""); stream.Position = 0; stream.Write(ms.GetBuffer(), 0, (int)ms.Length); stream.Flush(); stream.Close(); //delete the map of the object MemoryMappedFile oMMf = new MemoryMappedFile(); if (oMMf.Open(MapAccess.FileMapAllAccess, ObjName)) { oMMf.Close(); oMMf.Dispose(); } if (System.IO.File.Exists(map.GetMMFDir() + ObjName + ".nat")) { System.IO.File.Delete(map.GetMMFDir() + ObjName + ".nat"); } } }
public virtual void CustomAwake(MemoryBridge memoryBridge, string limbName, VesselControl vesselControl) { Debug.Log("Custom Awake Limb : " + limbName); this.memoryBridge = memoryBridge; this.vesselControl = vesselControl; limbFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, limbName); float byteCount; float servoCount; using (Stream mapStream = limbFile.MapView(MapAccess.FileMapAllAccess, 0, 16)) { var floatBuffer = new byte[4]; mapStream.Read(floatBuffer, 0, 4); byteCount = BitConverter.ToSingle(floatBuffer, 0); mapStream.Read(floatBuffer, 0, 4); servoCount = BitConverter.ToSingle(floatBuffer, 0); } var servosMirror = new List <RoboticServoMirror>(); ground = Instantiate(GameObject.Find("Ground")).transform; using (Stream mapStream = limbFile.MapView(MapAccess.FileMapAllAccess, 0, (int)byteCount)) { mapStream.Position = 16; for (int i = 0; i < servoCount; i++) { //servo name var floatBuffer = new byte[4]; mapStream.Read(floatBuffer, 0, 4); var stringByteLength = BitConverter.ToSingle(floatBuffer, 0); var stringBuffer = new byte[(int)stringByteLength]; mapStream.Read(stringBuffer, 0, stringBuffer.Length); string servoName = ASCIIEncoding.ASCII.GetString(stringBuffer); //servo parent id mapStream.Read(floatBuffer, 0, 4); var partID = BitConverter.ToSingle(floatBuffer, 0); mapStream.Read(floatBuffer, 0, 4); var parentID = BitConverter.ToSingle(floatBuffer, 0); foreach (var part in vesselControl.vessel.parts) { if (part.ID == partID) { var newServo = part.gameObject.AddComponent(typeof(RoboticServoMirror)) as RoboticServoMirror; newServo.CustomStart(servoName, memoryBridge, this, (int)parentID); servosMirror.Add(newServo); } } } } foreach (var servo in servosMirror) { servo.CreateBaseAnchor(); } CreateRoboticLegs(servosMirror); }
void UpdateHeaderFile() { // Debug.Log("update header file " + keysFloat.Count); using (var headerStream = fileHeader.MapView(MapAccess.FileMapAllAccess, 0, 16)) { headerStream.Write(BitConverter.GetBytes(memoryBridge.clientTransmittingFloat), 0, 4); headerStream.Write(BitConverter.GetBytes((float)keysFloat.Count), 0, 4); headerStream.Write(BitConverter.GetBytes((float)byteCountKeyFloat), 0, 4); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Process the file /// </summary> /// <returns><c>true</c> if it's a PE file, otherwise <c>false</c>.</returns> /// ------------------------------------------------------------------------------------ protected bool ProcessFile() { FileInfo fileInfo = new FileInfo(m_fileName); m_stream = m_mappedFile.MapView(MapAccess.FileMapCopy, 0, (int)fileInfo.Length); Debug.WriteLine(string.Format("Position={0}, Length={1}", m_stream.Position, m_stream.Length)); m_reader = new BinaryReader(m_stream); m_writer = new BinaryWriter(m_stream); // MS-DOS Stub (Image Only) m_fImageFile = ProcessMsDosStub(); if (!m_fImageFile) { return(false); } short nSections; short sizeOfOptionalHeader = ProcessCoffFileHeader(out nSections); long posAfterFileHeader = m_stream.Position; if (sizeOfOptionalHeader > 0) { ProcessOptionalHeader(); } m_stream.Position = posAfterFileHeader + sizeOfOptionalHeader; ProcessSections(nSections); m_stream.Position = 0; return(true); }
public T read() { if (mapFile == null) { try { mapFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, fileName); } catch { mapFile = null; throw new Exception("File " + fileName + " is not opened yet."); } } reader = mapFile.MapView(MapAccess.FileMapRead, 0, 8 * 1024); try { mutex = Mutex.OpenExisting("MyMutex"); } catch { mutex = new Mutex(false, "MyMutex", out mutexCreated); } if (mutexCreated == false) { Console.WriteLine("Mutex error"); //return; } return(getObjectFromMMF()); }
public void TestMMFViewSeeking() { string filename = Path.GetTempFileName(); MemoryMappedFile map = MemoryMappedFile.Create(filename, MapProtection.PageReadWrite, MAX_BYTES); using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES)) { view.WriteByte(0x12); // seek from start of view view.Seek(12, SeekOrigin.Begin); Assert.AreEqual(12, (int)view.Position); // Seek from current pos view.Seek(1, SeekOrigin.Current); Assert.AreEqual(13, (int)view.Position); // seek from end view.Seek(-1, SeekOrigin.End); Assert.AreEqual(MAX_BYTES - 1, (int)view.Position); try { // no seeking past end of stream view.Seek(1, SeekOrigin.End); Assert.Fail("Seeked past end of stream"); } catch (FileMapIOException) { } } map.Close(); }
private void writeHeaderBlank() { //////////////////////////////////////////////// // HEADER = [4 bytes blob len] + [8 byte ID] + [4 bytes Capacity] + [4 bytes Count] + [980 byte fields] = 1,000 // [4 bytes blob LEN] byte[] _byteBlobLEN = BitConverter.GetBytes(m_BlobLEN); // [8 byte ID] m_FileID = long.Parse(DateTime.Now.ToString("yyMMddHHmmssfff")); byte[] _byteFileID = BitConverter.GetBytes(m_FileID).ToArray(); // [4 bytes Capacity] byte[] _byteCapacity = BitConverter.GetBytes(m_Capacity); // [4 bytes Count] byte[] _byteCount = BitConverter.GetBytes(m_Count); // [980 byte fields] byte[] bm; using (var ms = new MemoryStream()) { new JsonSerializer().Serialize(new BsonWriter(ms), Model); bm = ms.ToArray(); } byte[] bm7 = SevenZip.Compression.LZMA.SevenZipHelper.Compress(bm); List <byte> _byteFields = new List <byte>(); _byteFields.AddRange(BitConverter.GetBytes(bm7.Length)); _byteFields.AddRange(bm7); _byteFields.AddRange(new byte[980 - _byteFields.Count]); TypeDynamic = buildTypeDynamic(Model); List <byte> ls = new List <byte>(); ls.AddRange(_byteBlobLEN); ls.AddRange(_byteFileID); ls.AddRange(_byteCapacity); ls.AddRange(_byteCount); ls.AddRange(_byteFields); using (Stream view = m_mapFile.MapView(MapAccess.FileMapWrite, 0, ls.Count)) view.Write(ls.ToArray(), 0, ls.Count); }
/// <summary> /// Creates a new profiler using a process start info of an executable and a data writer. /// </summary> public Profiler(ProcessStartInfo info, IProfilingDataWriter dataWriter, ProfilerOptions options) { if (dataWriter == null) { throw new ArgumentNullException("dataWriter"); } if (info == null) { throw new ArgumentNullException("info"); } if (!DetectBinaryType.IsDotNetExecutable(info.FileName)) { throw new ProfilerException("File is not a valid .NET executable file!"); } this.profilerOptions = options; this.is64Bit = DetectBinaryType.RunsAs64Bit(info.FileName); this.profilerOutput = new StringBuilder(); this.performanceCounters = options.Counters; foreach (var counter in performanceCounters) { counter.Reset(); } this.dataWriter = dataWriter; this.threadListMutex = new Mutex(false, MutexId); this.accessEventHandle = new EventWaitHandle(true, EventResetMode.ManualReset, this.AccessEventId); this.psi = info; this.psi.UseShellExecute = false; // needed to get env vars working! this.psi.EnvironmentVariables["SharedMemoryName"] = SharedMemoryId; this.psi.EnvironmentVariables["MutexName"] = MutexId; // mutex for process pause/continue sychronization this.psi.EnvironmentVariables["AccessEventName"] = AccessEventId; // name for access event of controller this.psi.EnvironmentVariables["COR_ENABLE_PROFILING"] = "1"; // enable profiling; 0 = disable this.psi.EnvironmentVariables["COR_PROFILER"] = ProfilerGuid; // GUID for the profiler this.psi.EnvironmentVariables["COMPLUS_ProfAPI_ProfilerCompatibilitySetting"] = "EnableV2Profiler"; // enable CLR 2.0 for CLR 4.0 file = MemoryMappedFile.CreateSharedMemory(SharedMemoryId, profilerOptions.SharedMemorySize); fullView = file.MapView(0, profilerOptions.SharedMemorySize); this.dataWriter.ProcessorFrequency = GetProcessorFrequency(); this.logger = new Thread(new ParameterizedThreadStart(Logging)); this.logger.Name = "Logger"; this.logger.IsBackground = true; // don't let the logger thread prevent our process from exiting this.dataCollector = new Thread(new ThreadStart(DataCollection)); this.dataCollector.Name = "DataCollector"; this.dataCollector.IsBackground = true; }
public void TestNonBackedMMF() { try { MemoryMappedFile map = MemoryMappedFile.Create(MapProtection.PageReadWrite, MAX_BYTES); using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES)) { WriteBytesToStream(view, MAX_BYTES); } using (Stream view = map.MapView(MapAccess.FileMapRead, 0, MAX_BYTES / 2)) { VerifyBytesInStream(view, MAX_BYTES / 2); } map.Close(); } catch (FileMapIOException e) { Assert.Fail("Write error: " + e); } }
public void TestMMFFileWrite() { try { string filename = Path.GetTempFileName(); MemoryMappedFile map = MemoryMappedFile.Create(filename, MapProtection.PageReadWrite, MAX_BYTES); using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES)) { WriteBytesToStream(view, MAX_BYTES); } using (Stream view = map.MapView(MapAccess.FileMapRead, 0, MAX_BYTES / 2)) { VerifyBytesInStream(view, MAX_BYTES / 2); } map.Close(); } catch (FileMapIOException e) { Assert.Fail("Write error: " + e); } }
// List<LimbControllersIK> IKlimbs; public void CustomAwake(MemoryBridge memoryBridge, VesselControl vesselControl, ref List <LimbController> limbs) { IRFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "IRFile" + memoryBridge.fileName); limbs = new List <LimbController>(); float byteCount; float limbCount; using (Stream mapStream = IRFile.MapView(MapAccess.FileMapAllAccess, 0, 16)) { var floatBuffer = new byte[4]; mapStream.Read(floatBuffer, 0, 4); byteCount = BitConverter.ToInt32(floatBuffer, 0); mapStream.Read(floatBuffer, 0, 4); limbCount = BitConverter.ToInt32(floatBuffer, 0); } Debug.Log("vessel has limbs " + limbCount); using (Stream mapStream = IRFile.MapView(MapAccess.FileMapAllAccess, 0, (int)byteCount)) { mapStream.Position = 16; for (int i = 0; i < limbCount; i++) { var floatBuffer = new byte[4]; mapStream.Read(floatBuffer, 0, 4); var stringByteLength = BitConverter.ToSingle(floatBuffer, 0); var stringBuffer = new byte[(int)stringByteLength]; mapStream.Read(stringBuffer, 0, stringBuffer.Length); string limbName = ASCIIEncoding.ASCII.GetString(stringBuffer); var newLimbObject = new GameObject(); newLimbObject.name = limbName; newLimbObject.transform.SetParent(vesselControl.vessel.transform); var newLimb = newLimbObject.AddComponent(typeof(LimbController)) as LimbController; newLimb.CustomAwake(memoryBridge, limbName, vesselControl); limbs.Add(newLimb); // Debug.Log("Add limb " + limbName); } } }
/// <summary> /// /// </summary> public virtual void Open() { if (m_IsOpen) { Close(); } // m_File = MemoryMappedFile.Create(null /*m_Address*/, MapProtection.PageReadWrite, m_MaxSize, m_Address); m_Stream = m_File.MapView(MapAccess.FileMapAllAccess, 0 /*m_Offset*/, m_MaxSize /*m_Count*/) as MapViewStream; // m_IsOpen = true; }
public object Post() { int port = 0; MemoryMappedFile map = MemoryMappedFile.Create(MapProtection.PageReadWrite, 4, this.Name); byte[] buf = new byte[4]; using (Stream view = map.MapView(MapAccess.FileMapRead, 0, 4)) view.Read(buf, 0, 4); port = BitConverter.ToInt32(buf, 0); return(Post("http://127.0.0.1:" + port.ToString())); }
public void WriteAndReadFromBufferUsingMemoryMappedFile() { using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateSharedMemory("Local\\TestMemory", 1024)) { using (UnmanagedMemory view1 = mmf1.MapView(0, 1024)) { using (UnmanagedCircularBuffer ncb = UnmanagedCircularBuffer.Create(view1.Start, (int)view1.Length)) { using (Stream ws = ncb.CreateWritingStream()) { ws.WriteByte(0x42); } using (MemoryMappedFile mmf2 = MemoryMappedFile.Open("Local\\TestMemory")) { using (UnmanagedMemory view2 = mmf1.MapView(0, 1024)) { Assert.AreNotEqual(view1.Start, view2.Start); using (UnmanagedCircularBuffer ncb2 = UnmanagedCircularBuffer.Open(view2.Start)) { using (Stream rs = ncb2.CreateReadingStream()) { Assert.AreEqual(0x42, rs.ReadByte()); } } } } } } } }
public static void Initialize() { try { mappedFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "Local\\BROKENGEKI_SHARED_BUFFER"); NekoClient.Logging.Log.Info("Brokengeki shared memory exists, opening..."); } catch (FileMapIOException) { NekoClient.Logging.Log.Info("Brokengeki shared memory does not exist, creating..."); mappedFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, 256, "Local\\BROKENGEKI_SHARED_BUFFER"); } mapViewStream = (MapViewStream)mappedFile.MapView(MapAccess.FileMapAllAccess, 0, 256); }
/// <summary> /// GetObject return the object from MMF /// </summary> /// <param name="objName"></param> /// <returns></returns> public object GetObject(string objName) { MemoryMappedFile map = new MemoryMappedFile(); MemoryMappedFile mapOfName = new MemoryMappedFile(); System.Collections.Hashtable oFilesMap; try { oMutex.WaitOne(); if (!map.OpenEx(ObjectNamesMMF + ".NAT", MapProtection.PageReadOnly, ObjectNamesMMF, MapAccess.FileMapRead)) { throw new Exception("No Desc FileFound"); } BinaryFormatter bf = new BinaryFormatter(); Stream mmfStream = map.MapView(MapAccess.FileMapRead, 0, 0, ""); mmfStream.Position = 0; //mmfStream.Close (); oFilesMap = bf.Deserialize(mmfStream) as Hashtable; long StartPosition = mmfStream.Position; if (!oFilesMap.ContainsKey(objName)) { throw new Exception("No Name Found"); } if (!mapOfName.OpenEx(oFilesMap[objName].ToString() + ".NAT", MapProtection.PageReadOnly, oFilesMap[objName].ToString(), MapAccess.FileMapRead)) { throw new Exception("No Name File Found"); } mmfStream.Close(); mmfStream = null; mmfStream = mapOfName.MapView(MapAccess.FileMapRead, 0, 0, oFilesMap[objName].ToString() + ".NAT"); mmfStream.Position = 0; //mmfStream.SetLength (80000); object oRV = bf.Deserialize(mmfStream) as object; mmfStream.Close(); return(oRV); } catch (Exception e) { return(null); //throw new Exception("Cannot create File "+ objName,e); } finally { oMutex.ReleaseMutex(); } }
public void TestMMFViewSize() { string filename = Path.GetTempFileName(); MemoryMappedFile map = MemoryMappedFile.Create(filename, MapProtection.PageReadWrite, MAX_BYTES); using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES)) { view.Seek(MAX_BYTES, SeekOrigin.Begin); // no writing past end of view view.WriteByte(0x01); Assert.AreEqual(MAX_BYTES, (int)view.Position); // no reading past end of stream Assert.AreEqual(-1, view.ReadByte()); } map.Close(); }
/// <summary> /// create a MMF and serialize the object in to. /// </summary> /// <param name="InObject"></param> /// <param name="obectName"></param> /// <param name="ObjectSize"></param> private void WriteObjectToMMF(object InObject, string obectName, int ObjectSize) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, InObject); oMutex.WaitOne(); MemoryMappedFile map = new MemoryMappedFile(obectName + ".nat", MapProtection.PageReadWrite, MapAccess.FileMapAllAccess, ms.Length, obectName); MapViewStream stream = map.MapView(MapAccess.FileMapAllAccess, 0, (int)ms.Length, ""); stream.Write(ms.GetBuffer(), 0, (int)ms.Length); stream.Flush(); stream.Close(); oMutex.ReleaseMutex(); }
public UnmanagedProfilingDataSet LoadDataSet(int index) { if (index < 0 || index >= streamInfos.Count) { throw new IndexOutOfRangeException("index needs to be between 0 and " + (streamInfos.Count - 1) + "\nActual value: " + index); } if (mmf == null) { throw new InvalidOperationException("All writers have to be closed before reading the data from the database!"); } return(new DataSet(this, mmf.MapView(streamInfos[index].StreamStartPosition, streamInfos[index].StreamLength), streamInfos[index].NativeStartPosition, streamInfos[index].NativeRootFuncInfoStartPosition, streamInfos[index].IsFirst)); }
private bool OpenOrCreateFile() { try { if (File.Exists(m_FilePath)) { ///////////////////////////////////////////////// // OPEN m_FilePath FileInfo fi = new FileInfo(m_FilePath); m_FileSize = (int)fi.Length; m_mapFile = MemoryMappedFile.Create(m_FilePath, MapProtection.PageReadWrite, m_FileSize); if (m_FileSize > m_HeaderSize) { byte[] buf = new byte[m_FileSize]; using (Stream view = m_mapFile.MapView(MapAccess.FileMapRead, 0, m_FileSize)) view.Read(buf, 0, m_FileSize); bool val = bindHeader(buf); if (val) { m_mapPort = MemoryMappedFile.Create(MapProtection.PageReadWrite, 4, Model.Name); m_FileName = Model.Name + ".df"; return(true); } } } else { ///////////////////////////////////////////////// // CREATE NEW m_FilePath m_Capacity = m_BlobGrowSize; m_FileSize = m_HeaderSize + (m_Capacity * m_BlobSizeMax) + 1; m_mapFile = MemoryMappedFile.Create(m_FilePath, MapProtection.PageReadWrite, m_FileSize); //string fs = _model.Name + ";" + string.Join(",", _model.Fields.Select(x => ((int)x.Type).ToString() + x.Name).ToArray()); writeHeaderBlank(); return(true); } } catch { } return(false); }
private void http_Init() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); Port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); using (Stream view = m_mapPort.MapView(MapAccess.FileMapWrite, 0, 4)) view.Write(BitConverter.GetBytes(Port), 0, 4); listener = new HttpListener(); listener.Prefixes.Add("http://*:" + Port.ToString() + "/"); listener.Start(); listener.BeginGetContext(ProcessRequest, listener); }
T openMemoryFileAndReadData() { if (mapFile == null) { try { mapFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, fileName); UnityEngine.Debug.Log("read mutex e dhukse"); } catch { UnityEngine.Debug.Log("mmf read exception"); mapFile = null; throw new Exception("File " + fileName + " is not opened yet."); } } reader = mapFile.MapView(MapAccess.FileMapRead, 0, 8 * 1024); UnityEngine.Debug.Log("mmf read"); return(getObjectFromMMF()); }
// Use this for initialization void Start1() { //MemoryMappedFile memMap = MemoryMappedFile.Create(MapProtection.PageReadWrite, 512, "TestMemMap3"); //if (memMap == null) // Debug.Log("streamwriter null"); //Debug.Log(memMap); //using (Stream mapStream = memMap.MapView(MapAccess.FileMapAllAccess, 0, 512)) //{ // Debug.Log(mapStream); // // StreamReader streamReader = new StreamReader(mapStream); // StreamWriter streamWriter = new StreamWriter(mapStream); // if (streamWriter == null) // Debug.Log("streamwriter null"); // streamWriter.WriteLine("yoo"); // streamWriter.Flush(); // mapStream.Flush(); // Debug.Log("can write " + mapStream.CanWrite); //} MemoryMappedFile memFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "TestMemMap3"); if (memFile == null) { Debug.Log("memfile null"); } using (Stream mapStream1 = memFile.MapView(MapAccess.FileMapAllAccess, 0, 512)) { Debug.Log("can read " + mapStream1.CanRead); StreamReader streamReader = new StreamReader(mapStream1); if (streamReader == null) { Debug.Log("streamReader null"); } Debug.Log("line " + streamReader.ReadToEnd()); //var bytes = mapStream1.BeginRead() } memFile.Dispose(); }
private void openOrCreateMemoryFileAndWriteData(T data) { try { mapFile = MemoryMappedFile.Open(MapAccess.FileMapWrite, fileName); } catch { mapFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, 8 * 1024, fileName); } char[] charArrayOfObject = serializeToXml <T>(data).ToCharArray(); Stream writer = mapFile.MapView(MapAccess.FileMapWrite, 0, charArrayOfObject.Length); for (int i = 0; i < charArrayOfObject.Length; i++) { writer.WriteByte((byte)charArrayOfObject[i]); } writer.Flush(); writer.Close(); }
void Update() { if (!receivingResponce) //IS THE CLIENT RESPONDING { Debug.Log("client file empty"); //camFeedFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, textureByte.Length, "CamFeedFile" + fileName + this.memoryBridge.cameraFeeds.Count); camFeedFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "CamFeedFile" + fileName + memoryBridge.cameraFeeds.Count); if (camFeedFile != null) { _receivingResponce = true; BuildCamera(); } } else { Debug.Log("cam feed update"); memoryBridge.SetVector3("CamLocalPos" + fileName + memoryBridge.cameraFeeds.Count, cameraRig.localPosition); memoryBridge.SetVector3("CamLocalEuler" + fileName + memoryBridge.cameraFeeds.Count, cameraRig.localEulerAngles); /////WORKS//// using (Stream camStream = camFeedFile.MapView(MapAccess.FileMapAllAccess, 0, feedByteCount)) { byte[] buffer = new byte[feedByteCount]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = camStream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } var byteArray = ms.ToArray(); readTex.LoadRawTextureData(byteArray); } } readTex.Apply(); meshRenderer.material.SetTexture("_MainTex", readTex); } }
void BuildVessel() { var kspPartList = vessel.Parts; partList = new List <MemoryPart>(); var byteArrayList = new List <byte[]>(); int byteCount = 0; foreach (var part in kspPartList) { // Debug.Log("Part name to examine " + part.name); if (part.name != "strutConnector") { var newPart = new MemoryPart(part, vesselControl); partList.Add(newPart); byteCount += newPart.byteCount; } } //for the header //+ 8 bytes for header //*12 bytes for VesselOffset //*12 bytes for PartScale //*12 bytes for Rotation byteCount += 8; Debug.Log("vessel file byte count: " + byteCount); Debug.Log("vessel mesh count: " + partList.Count); vesselFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCount, "VesselFile" + memoryBridge.fileName); using (Stream mapStream = vesselFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount)) { var byteCountPackage = BitConverter.GetBytes(byteCount); mapStream.Write(byteCountPackage, 0, 4); var partCount = BitConverter.GetBytes(partList.Count); mapStream.Write(partCount, 0, 4); foreach (var memPart in partList) { Debug.Log("start writing part at position " + mapStream.Position); //THESE BYTES ARE ALLOCATED IN THE CLASS mapStream.Write(BitConverter.GetBytes(memPart.uniqueID), 0, 4); mapStream.Write(BitConverter.GetBytes(memPart.parentID), 0, 4); mapStream.Write(BitConverter.GetBytes((float)memPart.meshList.Count), 0, 4); //THESE BYTES ARE ALLOCATED IN THE CLASS mapStream.Write(BitConverter.GetBytes((float)memPart.offset.x), 0, 4); mapStream.Write(BitConverter.GetBytes((float)memPart.offset.y), 0, 4); mapStream.Write(BitConverter.GetBytes((float)memPart.offset.z), 0, 4); //THESE BYTES ARE ALLOCATED IN THE CLASS mapStream.Write(BitConverter.GetBytes((float)memPart.rotOffset.x), 0, 4); mapStream.Write(BitConverter.GetBytes((float)memPart.rotOffset.y), 0, 4); mapStream.Write(BitConverter.GetBytes((float)memPart.rotOffset.z), 0, 4); //for name, allocated in class var bytePackage = BitConverter.GetBytes((float)memPart.nameBytePackage.Length); mapStream.Write(bytePackage, 0, 4); mapStream.Write(memPart.nameBytePackage, 0, memPart.nameBytePackage.Length); foreach (var filter in memPart.meshList) { //Debug.Log("start writing filter at position " + mapStream.Position); //THESE BYTES ARE ALLOCATED IN THE CLASS mapStream.Write(BitConverter.GetBytes((float)filter.vesselPartOffset.x), 0, 4); mapStream.Write(BitConverter.GetBytes((float)filter.vesselPartOffset.y), 0, 4); mapStream.Write(BitConverter.GetBytes((float)filter.vesselPartOffset.z), 0, 4); //THESE BYTES ARE ALLOCATED IN THE CLASS var partEulerAngle = filter.vesselPartLocalEuler; //mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.w), 0, 4); mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.x), 0, 4); mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.y), 0, 4); mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.z), 0, 4); //THESE BYTES ARE ALLOCATED IN THE CLASS var partScale = filter.lossyScale; mapStream.Write(BitConverter.GetBytes((float)partScale.x), 0, 4); mapStream.Write(BitConverter.GetBytes((float)partScale.y), 0, 4); mapStream.Write(BitConverter.GetBytes((float)partScale.z), 0, 4); //THESE BYTES ARE ALLOCATED IN THE CLASS mapStream.Write(BitConverter.GetBytes((float)filter.byteArrMesh.Length), 0, 4); // Debug.Log(memPart.name + " has a mesh byte array count of " + (filter.byteArrMesh.Length)); // mapStream.Write(BitConverter.GetBytes((float)filter.byteArrMesh.Length), 0, 4); mapStream.Write(filter.byteArrMesh, 0, filter.byteArrMesh.Length); } } } Debug.Log("Control Awake and Running"); }
public VesselControl.Vessel DrawVessel(MemoryBridge memoryBridge, Material drawMat, string vesselName) { VesselControl.Vessel newVessel; this.memoryBridge = memoryBridge; this.vesselName = vesselName; var binFormatter = new BinaryFormatter(); var mStream = new MemoryStream(); meshList = new List <Mesh>(); parts = new List <Part>(); // partList = new List<VesselPart>(); var vesselObject = new GameObject(); vesselObject.name = vesselName; vessel = vesselObject.transform; vessel.SetParent(transform); vessel.position = Vector3.zero; vessel.localEulerAngles = Vector3.zero; //DebugVector.DrawVector(vessel); var modelObject = new GameObject(); modelObject.name = "Vessel Offset"; vesselOffset = modelObject.transform; vesselOffset.SetParent(vessel); vesselOffset.position = Vector3.zero; vesselOffset.localEulerAngles = Vector3.zero; if (vesselFile == null) { vesselFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "VesselFile" + memoryBridge.fileName); } if (vesselFile == null) { Debug.Log("file is null"); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #endif } int byteCount = 0; int partCount = 0; using (Stream mapStream = vesselFile.MapView(MapAccess.FileMapAllAccess, 0, 8)) { var totalByteBuffer = new byte[4]; var partCountBuffer = new byte[4]; mapStream.Read(totalByteBuffer, 0, 4); mapStream.Read(partCountBuffer, 0, 4); byteCount = BitConverter.ToInt32(totalByteBuffer, 0); partCount = BitConverter.ToInt32(partCountBuffer, 0); } using (Stream mapStream = vesselFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount)) { mapStream.Position = 8; for (int i = 0; i < partCount; i++) { List <MeshRenderer> meshRenderers = new List <MeshRenderer>(); //part unique id var totalpartBuffer = new byte[4]; mapStream.Read(totalpartBuffer, 0, 4); var uniqueID = BitConverter.ToSingle(totalpartBuffer, 0); //parent unique id totalpartBuffer = new byte[4]; mapStream.Read(totalpartBuffer, 0, 4); var parentUniqueID = BitConverter.ToSingle(totalpartBuffer, 0); //filter count totalpartBuffer = new byte[4]; mapStream.Read(totalpartBuffer, 0, 4); var filterCount = BitConverter.ToSingle(totalpartBuffer, 0); GameObject newPart = new GameObject(); var newPartObject = newPart.AddComponent(typeof(Part)) as Part; Vector3 vesselPartOffset = Vector3.zero; var tempBuffer = new Byte[4]; mapStream.Read(tempBuffer, 0, 4); vesselPartOffset.x = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); vesselPartOffset.y = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); vesselPartOffset.z = BitConverter.ToSingle(tempBuffer, 0); newPart.transform.localPosition = vesselPartOffset; //rot offset Vector3 vesselPartRotOffset = Vector3.zero; tempBuffer = new Byte[4]; mapStream.Read(tempBuffer, 0, 4); vesselPartRotOffset.x = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); vesselPartRotOffset.y = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); vesselPartRotOffset.z = BitConverter.ToSingle(tempBuffer, 0); newPart.transform.localEulerAngles = vesselPartRotOffset; //part name mapStream.Read(tempBuffer, 0, 4); var stringByteLength = BitConverter.ToSingle(tempBuffer, 0); var stringBuffer = new byte[(int)stringByteLength]; mapStream.Read(stringBuffer, 0, stringBuffer.Length); newPartObject.kspPartName = ASCIIEncoding.ASCII.GetString(stringBuffer); GameObject meshObjects = new GameObject(); meshObjects.name = "Mesh Objects"; newPartObject.partMeshes = meshObjects; meshObjects.transform.SetParent(newPart.transform); meshObjects.transform.localEulerAngles = Vector3.zero; for (int k = 0; k < filterCount; k++) { //Debug.Log("start writing filter at " + mapStream.Position); var newMesh = Instantiate(Resources.Load("BlankPart", typeof(GameObject))) as GameObject; newMesh.transform.SetParent(newPart.transform); meshRenderers.Add(newMesh.GetComponent <MeshRenderer>()); newMesh.GetComponent <MeshRenderer>().material = drawMat; Vector3 posVector = Vector3.zero; tempBuffer = new Byte[4]; mapStream.Read(tempBuffer, 0, 4); posVector.x = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); posVector.y = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); posVector.z = BitConverter.ToSingle(tempBuffer, 0); newMesh.transform.localPosition = posVector; var localEuler = Vector3.zero; // tempBuffer = new Byte[4]; mapStream.Read(tempBuffer, 0, 4); localEuler.x = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); localEuler.y = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); localEuler.z = BitConverter.ToSingle(tempBuffer, 0); newMesh.transform.localEulerAngles = localEuler; Vector3 scaleVector = Vector3.zero; // tempBuffer = new Byte[4]; mapStream.Read(tempBuffer, 0, 4); scaleVector.x = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); scaleVector.y = BitConverter.ToSingle(tempBuffer, 0); mapStream.Read(tempBuffer, 0, 4); scaleVector.z = BitConverter.ToSingle(tempBuffer, 0); newMesh.transform.localScale = scaleVector; var lengthBuffer = new Byte[4]; mapStream.Read(lengthBuffer, 0, 4); var byteMeshLength = BitConverter.ToSingle(lengthBuffer, 0); var meshBuffer = new Byte[(int)byteMeshLength]; mapStream.Read(meshBuffer, 0, (int)byteMeshLength); newMesh.GetComponent <MeshFilter>().mesh = MeshSerializer.ReadMesh(meshBuffer); //not sure why this doesnt work up top, but too lazy to figure it out newMesh.transform.SetParent(meshObjects.transform); } newPartObject.CustomAwake((int)uniqueID, (int)parentUniqueID, vesselName, meshRenderers); parts.Add(newPartObject); } } newVessel.transform = vessel; newVessel.parts = parts; newVessel.meshOffset = vesselOffset; foreach (var part in newVessel.parts) { part.vessel = newVessel; part.FindParent(); } return(newVessel); }
/// <summary> /// this function will /// 1) open exsisting (if not create) MMF that hold all the MMf names for each object /// 2) look if aname allready exist /// 3) if exist /// -Delete the MMF /// -create new MMF /// -Enter the onject into /// if not /// -create new MMF /// -Enter the onject into /// -enter the new name and MMF name into MMF of object and MMF name /// </summary> /// <param name="objName"></param> /// <param name="inObject"></param> public void AddObject(string objName, object inObject, bool UpdateDomain) { MemoryMappedFile map = new MemoryMappedFile(); System.Collections.Hashtable oFilesMap; System.IntPtr oAtom = System.IntPtr.Zero; string strIps = ""; try { if (!map.OpenEx(ObjectNamesMMF + ".nat", MapProtection.PageReadWrite, ObjectNamesMMF, MapAccess.FileMapAllAccess)) { //Create MMF for the object and serialize it WriteObjectToMMF(inObject, objName, 0); //create hashtable oFilesMap = new System.Collections.Hashtable(); //add object name and mmf name to hash oFilesMap.Add(objName, objName); //create main MMF WriteObjectToMMF(oFilesMap, ObjectNamesMMF, 0); } else { BinaryFormatter bf = new BinaryFormatter(); Stream mmfStream = map.MapView(MapAccess.FileMapRead, 0, 0, ""); mmfStream.Position = 0; oFilesMap = bf.Deserialize(mmfStream) as Hashtable; long StartPosition = mmfStream.Position; if (oFilesMap.ContainsKey(objName)) { //name exist so we need to // open the MMF of the existing and update it MemoryMappedFile MemberMap = new MemoryMappedFile(); oMutex.WaitOne(); MemberMap.OpenEx(objName + ".nat", MapProtection.PageReadWrite, objName, MapAccess.FileMapAllAccess); //(MapAccess.FileMapAllAccess ,objName); MapViewStream stream = MemberMap.MapView(MapAccess.FileMapAllAccess, 0, (int)0, ""); bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, inObject); stream.Position = 0; stream.Write(ms.GetBuffer(), 0, (int)ms.Length); stream.Flush(); stream.Close(); oMutex.ReleaseMutex(); } else { //name not apear so we nedd to // craete new MMF file and serialize WriteObjectToMMF(inObject, objName, 0); oMutex.WaitOne(); MapViewStream stream = map.MapView(MapAccess.FileMapAllAccess, 0, (int)0, ""); // update the main HashTable oFilesMap.Add(objName, objName); // serialize new Hash bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, oFilesMap); stream.Position = 0; stream.Write(ms.GetBuffer(), 0, (int)ms.Length); stream.Flush(); stream.Close(); oMutex.ReleaseMutex(); } } } catch (Exception e) { throw new Exception("Cannot Open File " + objName, e); } finally { Win32MapApis.GlobalDeleteAtom(oAtom); } }
public void CustomStart(List <Part> parts, MemoryBridge memoryBridge) { Debug.Log("IR Manager custom start"); limbs = new List <RoboticArm>(); if (IRWrapper.IRController == null) { Debug.Log("IR3Controller is not null"); } Debug.Log(IRWrapper.IRController.ServoGroups.Count); foreach (IRWrapper.IControlGroup group in IRWrapper.IRController.ServoGroups) { Debug.Log("Servo Group : " + group.Name); if (group.Name.ToLower().Contains("ik")) { IRWrapper.IServo basePart = null; IRWrapper.IServo wristPart = null; foreach (var servo in group.Servos) { if (servo.Name.ToLower().Contains("base")) { basePart = servo; } if (servo.Name.ToLower().Contains("wrist")) { wristPart = servo; } } var newLimb = gameObject.AddComponent(typeof(RoboticArm)) as RoboticArm; newLimb.CustomAwake(group, basePart, wristPart, memoryBridge); limbs.Add(newLimb); byteCount += 4; byteCount += newLimb.limbName.Length; } } byteCount += 16; IRFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCount, "IRFile" + memoryBridge.fileName); using (Stream mapStream = IRFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount)) { var bytePackage = BitConverter.GetBytes(byteCount); mapStream.Write(bytePackage, 0, 4); bytePackage = BitConverter.GetBytes(limbs.Count); mapStream.Write(bytePackage, 0, 4); mapStream.Position = 16; foreach (var limb in limbs) { var nameBytePackage = Encoding.ASCII.GetBytes(limb.limbName); bytePackage = BitConverter.GetBytes((float)nameBytePackage.Length); mapStream.Write(bytePackage, 0, 4); mapStream.Write(nameBytePackage, 0, nameBytePackage.Length); } } //legs = new List<MechLeg>(); //foreach (IRWrapper.IControlGroup group in IRWrapper.IRController.ServoGroups) //{ // if (group.Name == "Leg One") // { // legOne = new MechLeg(memoryBridge, group, this, "Leg One"); // legs.Add(legOne); // } // else if (group.Name == "Leg Two") // { // legTwo = new MechLeg(memoryBridge, group, this, "Leg Two"); // legs.Add(legTwo); // } // else if (group.Name == "Leg Three") // { // legThree = new MechLeg(memoryBridge, group, this, "Leg Three"); // legs.Add(legThree); // } // else if (group.Name == "Leg Four") // { // legFour = new MechLeg(memoryBridge, group, this, "Leg Four"); // legs.Add(legFour); // } // else if (group.Name == "Leg Five") // { // legFive = new MechLeg(memoryBridge, group, this, "Leg Five"); // legs.Add(legFive); // } // else if (group.Name == "Leg Six") // { // legSix = new MechLeg(memoryBridge, group, this, "Leg Six"); // legs.Add(legSix); // } // else if (group.Name == "Arm") // { // armOne = new MechArm(memoryBridge, group, this); // } //} }
// List<Part> parts; public void CustomAwake(IRWrapper.IControlGroup limbGroup, IRWrapper.IServo servoBase, IRWrapper.IServo servoWrist, MemoryBridge memoryBridge) { this.memoryBridge = memoryBridge; limbName = limbGroup.Name + memoryBridge.fileName; limbServos = new List<RoboticServo>(); //Add wrist servo var newServo = servoBase.HostPart.gameObject.AddComponent(typeof(RoboticServo)) as RoboticServo; newServo.CustomStart(servoBase, memoryBridge); limbServos.Add(newServo); //parts = new List<Part>(); Part tempPart = servoBase.HostPart; bool done = false; int count = 0; do { count++; var armParts = tempPart.children; armParts.Remove(tempPart); foreach (var part in armParts) { Debug.Log(part.name + " is a child of " + tempPart.name); IRWrapper.IServo testServo = null; foreach (var servo in limbGroup.Servos) { if (part == servo.HostPart) { testServo = servo; //break; } } if (testServo != null) { tempPart = part; // if (!testServo.Name.ToLower().Contains("skip")) // { Debug.Log("found servo on part"); newServo = part.gameObject.AddComponent(typeof(RoboticServo)) as RoboticServo; newServo.CustomStart(testServo, memoryBridge); limbServos.Add(newServo); // } if (testServo.Name.ToLower().Contains("wrist")) { Debug.Log("wrist servo found"); wristServo = newServo; done = true; } //if (servo.Name.ToLower().Contains("wrist")) //{ // wristPart = servo; //} } } } while (count < 30); //newServo = gameObject.AddComponent(typeof(RoboticServo)) as RoboticServo; //newServo.CustomStart(servoWrist); //limbServos.Add(newServo); int byteCount = 0; Debug.Log(limbGroup.Name + " servo hierarchy " + limbServos.Count); for (int i = 0; i < limbServos.Count; i++) { Debug.Log(limbServos[i].servo.Name); string parentName = "null"; if (i != 0) { parentName = limbServos[i - 1].servoName; limbServos[i].parentID = limbServos[i - 1].servo.HostPart.gameObject.GetInstanceID(); limbServos[i].ParentSet(limbServos[i - 1].servo.HostPart.transform); } limbServos[i].parentServoName = parentName; byteCount += 8; //parent id byteCount += 4; byteCount += limbServos[i].servoName.Length; // byteCount += limbServos[i].parentServoName.Length; } byteCount += 16; LimbFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCount, limbName); using (Stream mapStream = LimbFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount)) { var bytePackage = BitConverter.GetBytes((float)byteCount); mapStream.Write(bytePackage, 0, 4); bytePackage = BitConverter.GetBytes((float)limbServos.Count); mapStream.Write(bytePackage, 0, 4); mapStream.Position = 16; for (int i = 0; i < limbServos.Count; i++) { var nameBytePackage = Encoding.ASCII.GetBytes(limbServos[i].servoName); bytePackage = BitConverter.GetBytes((float)nameBytePackage.Length); mapStream.Write(bytePackage, 0, 4); mapStream.Write(nameBytePackage, 0, nameBytePackage.Length); // nameBytePackage = Encoding.ASCII.GetBytes(limbServos[i].parentServoName); bytePackage = BitConverter.GetBytes((float)limbServos[i].servo.HostPart.gameObject.GetInstanceID()); mapStream.Write(bytePackage, 0, 4); // mapStream.Write(nameBytePackage, 0, nameBytePackage.Length); bytePackage = BitConverter.GetBytes((float)limbServos[i].parentID); mapStream.Write(bytePackage, 0, 4); } } //var contactPoint = memoryBridge.GetVector3(wristServo.servoName + "contactPoint"); //if (contactPoint != Vector3.zero) // { // Debug.Log("Set ground point to " + contactPoint); //wristServo.contactPoint = contactPoint; wristServo.CreateContactPoint(); // contactPointSet = true; //} }