コード例 #1
0
 //called when data for any output pin is requested
 public void Evaluate(int spreadMax)
 {
     FTextureOut.ResizeAndDispose(spreadMax, CreateTextureResource);
     for (int i = 0; i < spreadMax; i++)
     {
         var textureResource = FTextureOut[i];
         var info            = textureResource.Metadata;
         //recreate textures if resolution was changed
         if (info.Width != FWidthIn[i] || info.Height != FHeightIn[i])
         {
             textureResource.Dispose();
             textureResource = CreateTextureResource(i);
             info            = textureResource.Metadata;
         }
         //update textures if their wave count changed
         if (info.WaveCount != FWaveCountIn[i])
         {
             info.WaveCount = FWaveCountIn[i];
             textureResource.NeedsUpdate = true;
         }
         else
         {
             textureResource.NeedsUpdate = false;
         }
         FTextureOut[i] = textureResource;
     }
 }
コード例 #2
0
ファイル: QrCodeTextureNode.cs プロジェクト: vnmone/vvvv-sdk
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            FTextureOut.ResizeAndDispose(spreadMax, CreateTextureResource);
            for (int i = 0; i < spreadMax; i++)
            {
                var textureResource = FTextureOut[i];
                var info            = textureResource.Metadata;
                //recreate textures if resolution was changed
                if (info.PixelSize != FPixelSize[i] || info.Text != FText[i] || info.ECLevel != FErrorCorrectionLevel[i] || info.QZModules != FQuietZoneModules[i])
                {
                    textureResource.Dispose();
                    textureResource = CreateTextureResource(i);
                    info            = textureResource.Metadata;
                }

                //update textures if their colors changed
                if (FBackColor.IsChanged || FForeColor.IsChanged)
                {
                    ComputeQRCode(info, i);
                    textureResource.NeedsUpdate = true;
                }
                else
                {
                    textureResource.NeedsUpdate = false;
                }

                FTextureOut[i] = textureResource;
            }
        }
コード例 #3
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            FMeshOut.ResizeAndDispose(spreadMax, CreateMeshResource);
            for (int i = 0; i < spreadMax; i++)
            {
                var meshResource = FMeshOut[i];
                var meshData     = meshResource.Metadata;

                //recreate mesh
                if (meshData.Resolution != FResoIn[i] || FResetIn[i])
                {
                    meshResource.Dispose();
                    meshResource = CreateMeshResource(i);
                    meshData     = meshResource.Metadata;
                }

                //update mesh
                if (meshData.Randomness != FRandomizeIn[i])
                {
                    meshData.Randomness      = FRandomizeIn[i];
                    meshResource.NeedsUpdate = true;
                }
                else
                {
                    meshResource.NeedsUpdate = false;
                }
                FMeshOut[i] = meshResource;
            }
        }
コード例 #4
0
ファイル: AsTextureNode.cs プロジェクト: timpernagel/vvvv-sdk
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            FTextureOut.ResizeAndDispose(spreadMax, CreateTextureResource);

            for (int i = 0; i < spreadMax; i++)
            {
                var textureResource = FTextureOut[i];
                var info            = textureResource.Metadata;

                if (FApply[i])
                {
                    textureResource.Dispose();
                    textureResource = CreateTextureResource(i);
                    info            = textureResource.Metadata;

                    ReadBytes(info, i);
                    textureResource.NeedsUpdate = true;
                }
                else
                {
                    textureResource.NeedsUpdate = false;
                }

                FTextureOut[i] = textureResource;
            }
        }
コード例 #5
0
            //called when data for any output pin is requested
            public void Evaluate(int SpreadMax)
            {
                //FLogger.Log(LogType.Debug, FHDEHost.FrameTime.ToString() + "," + FHDEHost.RealTime.ToString());

                FOutTexture.ResizeAndDispose(1, CreateTextureResource);
                var textureResource = FOutTexture[0];
                var info            = textureResource.Metadata;

                if (!initialized || FInFragmentShader.IsChanged || FInFilename.IsChanged)
                {
                    textureResource.Dispose();
                    textureResource = CreateTextureResource();
                    info            = textureResource.Metadata;

                    Init();
                }

                if (resized)
                {
                    textureResource.Dispose();
                    textureResource = CreateTextureResource();
                    info            = textureResource.Metadata;

                    resized = false;
                }

                if (shaderProgram > 0 && FInPlay[0])
                {
                    Render();
                }

                FOutTexture[0] = textureResource;
            }
コード例 #6
0
        public void Evaluate(int SpreadMax)
        {
            SpreadMax = FDoSendIn.CombineWith(FMessageIn).CombineWith(FData1In).CombineWith(FData2In);

            FEventsOut.ResizeAndDispose(SpreadMax, () => new ManualMidiEvents());

            for (int i = 0; i < SpreadMax; i++)
            {
                var eventSender = FEventsOut[i] as ManualMidiEvents;
                var doSends     = FDoSendIn[i];
                var messages    = FMessageIn[i];
                var data1s      = FData1In[i];
                var data2s      = FData2In[i];

                var max = doSends.CombineWith(messages).CombineWith(data1s).CombineWith(data2s);

                //send all events
                for (int j = 0; j < max; j++)
                {
                    if (doSends[j])
                    {
                        eventSender.SendRawMessage((byte)messages[j], (byte)data1s[j], (byte)data2s[j]);
                    }
                }
            }
        }
コード例 #7
0
ファイル: PBKDF2Node.cs プロジェクト: rabbimaan/vvvv-sdk
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());
            FKeyGens.SliceCount = spreadMax;

            if (FPass.IsChanged || FKeyLength.IsChanged || FKeyIterations.IsChanged || FKeySalt.IsChanged)
            {
                for (int i = 0; i < spreadMax; i++)
                {
                    var outputStream = FStreamOut[i];

                    try
                    {
                        FKeyGens[i] = new KeyGenerator();
                        var key = FKeyGens[i].GenerateKey(FPass[i], FKeyLength[i], FKeyIterations[i], FKeySalt[i]);
                        outputStream.SetLength(0);
                        outputStream.Write(key, 0, key.Length);
                    }
                    catch (Exception e)
                    {
                        FLogger.Log(e);
                        outputStream.SetLength(0);
                        FErrorOut[i] = e.Message;
                    }
                }

                //this will force the changed flag of the output pin to be set
                FStreamOut.Flush(true);
            }
        }
コード例 #8
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            if (bitmaps == null || spreadMax != this.spreadMax)
            {
                bitmaps = new List <Bitmap>(spreadMax);
            }
            this.spreadMax        = spreadMax;
            FStatusOut.SliceCount = spreadMax;
            FTextureOut.ResizeAndDispose(spreadMax, CreateTextureResource);
            for (int i = 0; i < spreadMax; i++)
            {
                var textureResource = FTextureOut[i];

                int w = (int)FSizeIn[i].x;
                int h = (int)FSizeIn[i].y;

                if (w > 0 && h > 0 && FFontSizeIn[i] > 0)
                {
                    renderer          = new BitmapRenderer();
                    renderer.TextFont = new System.Drawing.Font(FFontIn[i].Name, FFontSizeIn[i]);
                    var info = textureResource.Metadata;
                    //recreate textures if resolution was changed
                    if (info.Width != w || info.Height != h)
                    {
                        textureResource.Dispose();
                        textureResource = CreateTextureResource(i);
                        info            = textureResource.Metadata;
                    }
                    if (info.Data != FDataIn[i] || info.Format != FFormatIn[i] ||
                        info.Width != w || info.Height != h ||
                        info.ShowText != FShowTextIn[i] || info.FontSize != FFontSizeIn[i] || firstFrame)
                    {
                        info.Data     = FDataIn[i];
                        info.Format   = FFormatIn[i];
                        info.ShowText = FShowTextIn[i];
                        info.FontSize = FFontSizeIn[i];
                        Bitmap bmp = new Bitmap(GenerateBarcodeImage(w, h, FDataIn[i], FFormatIn[i], !FShowTextIn[i], i));
                        if (bitmaps.Count <= i)
                        {
                            bitmaps.Add(bmp);
                        }
                        else
                        {
                            bitmaps[i] = bmp;
                        }
                        textureResource.NeedsUpdate = true;
                    }
                    else
                    {
                        textureResource.NeedsUpdate = false;
                    }
                }
                FTextureOut[i] = textureResource;
            }
            firstFrame = false;
        }
コード例 #9
0
 //called when data for any output pin is requested
 public void Evaluate(int spreadMax)
 {
     //ResizeAndDispose will adjust the spread length and thereby call
     //the given constructor function for new slices and Dispose on old
     //slices.
     FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());
     Tasks.SliceCount    = spreadMax;
     IOs.SliceCount      = spreadMax;
     FWorking.SliceCount = spreadMax;
     FError.SliceCount   = spreadMax;
     for (int i = 0; i < spreadMax; i++)
     {
         if (!FAsync[i])
         {
             FWorking[i] = false;
         }
         if (FCompress[i])
         {
             IOs[i]                = new CompressorIO();
             IOs[i].InBytes        = new byte[FStreamIn[i].Length];
             FStreamIn[i].Position = 0;
             FStreamIn[i].Read(IOs[i].InBytes, 0, (int)FStreamIn[i].Length);
             if (FAsync[i])
             {
                 Tasks[i] = new Task(CompressAsync, IOs[i]);
                 Tasks[i].Start();
             }
             else
             {
                 CompressAsync(IOs[i]);
                 FWorking[i]            = true;
                 FStreamOut[i].Position = 0;
                 FStreamOut[i].Write(IOs[i].OutBytes, 0, IOs[i].OutBytes.Length);
             }
         }
         if (Tasks[i] != null)
         {
             if (FAsync[i])
             {
                 if ((IOs[i].OutBytes != null) && FWorking[i])
                 {
                     FStreamOut[i].Position = 0;
                     FStreamOut[i].Write(IOs[i].OutBytes, 0, IOs[i].OutBytes.Length);
                 }
                 FWorking[i] = (!Tasks[i].IsCompleted) && (!Tasks[i].IsFaulted);
             }
             if (Tasks[i].Exception != null)
             {
                 FError[i] = Tasks[i].Exception.Message;
             }
         }
     }
     //this will force the changed flag of the output pin to be set
     FStreamOut.Flush(true);
 }
コード例 #10
0
ファイル: TriDESNodes.cs プロジェクト: timpernagel/vvvv-sdk
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            FStreamOut.ResizeAndDispose(spreadMax, () => new LeaveOpenStream());
            FEncryptors.SliceCount = spreadMax;
            FErrorOut.SliceCount   = spreadMax;

            for (int i = 0; i < spreadMax; i++)
            {
                var encryptor = FEncryptors[i];
                var key       = FKey[i].ToKeyBytes();
                var iv        = FIV[i].ToIvBytes();
                if (encryptor == null || !key.SequenceEqual(encryptor.Key) || !iv.SequenceEqual(encryptor.IV))
                {
                    try
                    {
                        encryptor      = new EncryptDecrypt(key, iv, FCipherMode[i], FPaddingMode[i]);
                        FEncryptors[i] = encryptor;
                    }
                    catch (Exception e)
                    {
                        encryptor    = null;
                        FErrorOut[i] = e.Message;
                    }
                }

                var outputStream = FStreamOut[i];
                var inputStream  = FStreamIn[i];

                if (encryptor != null && inputStream.Length > 0)
                {
                    try
                    {
                        inputStream.Position  = 0;
                        outputStream.Position = 0;
                        encryptor.EncryptOrDecrypt(inputStream, outputStream, FIsEncrypt, FBuffer);
                        FErrorOut[i] = string.Empty;
                    }
                    catch (Exception e)
                    {
                        FLogger.Log(e);
                        outputStream.SetLength(0);
                        FErrorOut[i] = e.Message;
                    }
                }
                else
                {
                    outputStream.SetLength(0);
                }
                FStreamOut[i] = outputStream;
            }
        }
コード例 #11
0
 public void Evaluate(int SpreadMax)
 {
     if (FInput.IsChanged)
     {
         FOutput.ResizeAndDispose(FInput.SliceCount, () => new MemoryComStream());
         FDataLength.SliceCount = FInput.SliceCount;
         for (int i = 0; i < FInput.SliceCount; i++)
         {
             if (FOutput[i] == null)
             {
                 FOutput[i] = new MemoryComStream();
             }
             if (FInput[i].Length < FOutput[i].Length)
             {
                 FOutput[i].SetLength(FInput[i].Length);
             }
             FInput[i].Position  = 0;
             FOutput[i].Position = 0;
             int dl = 0;
             int desiredNullCount = NullCount[i];
             int nullCount        = 0;
             while (true)
             {
                 int cbyte = FInput[i].ReadByte();
                 if (cbyte < 0)
                 {
                     desiredNullCount = 0;
                     break;
                 }
                 if (cbyte == 0)
                 {
                     nullCount++;
                     if (nullCount >= NullCount[i])
                     {
                         dl++;
                         break;
                     }
                 }
                 else
                 {
                     nullCount = 0;
                 }
                 FOutput[i].WriteByte((byte)cbyte);
                 dl++;
             }
             dl = dl - desiredNullCount;
             FOutput[i].SetLength(dl);
             FDataLength[i]      = dl;
             FInput[i].Position  = 0;
             FOutput[i].Position = 0;
             FOutput.Flush(true);
         }
     }
 }
コード例 #12
0
        //Stream tempStream;

        #region IPluginEvaluate Members

        public void Evaluate(int SpreadMax)
        {
            this.FOutValid.SliceCount = SpreadMax;

            if (this.FTextureIn.IsConnected)
            {
                if (this.RenderRequest != null)
                {
                    this.RenderRequest(this, this.FHost);
                }

                if (this.AssignedContext == null)
                {
                    this.FOutValid.SliceCount = 0; return;
                }
                //Do NOT cache this, assignment done by the host

                FStreamOut.ResizeAndDispose(SpreadMax, () => new MemoryStream());

                for (int i = 0; i < SpreadMax; i++)
                {
                    if (this.FTextureIn[i].Contains(this.AssignedContext) && this.FRead[i])
                    {
                        try
                        {
                            // "Clear" Pin
                            FStreamOut[i].Position = 0;
                            FStreamOut[i].SetLength(0);

                            Texture2D.ToStream(this.AssignedContext.CurrentDeviceContext, this.FTextureIn[i][this.AssignedContext].Resource, this.FInFormat[i], FStreamOut[i]);

                            FStreamOut.Flush(true);

                            this.FOutValid[i] = true;
                        }
                        catch (Exception ex)
                        {
                            FLogger.Log(ex);
                            this.FOutValid[i] = false;
                        }
                    }
                    else
                    {
                        this.FOutValid[i] = false;
                    }
                }
            }
            else
            {
                this.FOutValid.SliceCount = 0;
            }
        }
コード例 #13
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            //Note: Using the standard .NET MemoryStream would also work, but
            //since MemoryComStream delivered by VVVV.Utils implements the COM
            //IStream interface directly we save a little bit of overhead.
            //For details see https://vvvv.org/blog/raw-performance-speedup
            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryComStream());
            for (int i = 0; i < spreadMax; i++)
            {
                //get the input stream
                var inputStream = FStreamIn[i];
                //get the output stream (this works because of ResizeAndDispose above)
                var outputStream = FStreamOut[i];
                //get the number of bytes we should copy (avoid negative values)
                var count = Math.Max(FCountIn[i], 0);
                //see how many bytes should be copied from the input stream
                var numBytesToCopy = Math.Min(inputStream.Length, count);

                //reset the positions of the streams
                inputStream.Position  = 0;
                outputStream.Position = 0;

                //set the length of the output stream
                outputStream.SetLength(numBytesToCopy);

                //finally copy the data
                while (numBytesToCopy > 0)
                {
                    //make sure we don't read more than we need or more than
                    //our byte buffer can hold
                    var chunkSize = (int)Math.Min(numBytesToCopy, FBuffer.Length);
                    //the stream's read method returns how many bytes have actually
                    //been read into the buffer
                    var numBytesRead = inputStream.Read(FBuffer, 0, chunkSize);
                    //in case nothing has been read we need to leave the loop
                    //as we requested more than there was available
                    if (numBytesRead == 0)
                    {
                        break;
                    }
                    //write the number of bytes read to the output stream
                    outputStream.Write(FBuffer, 0, numBytesRead);
                    //decrease the total amount of bytes we still need to read
                    numBytesToCopy -= numBytesRead;
                }
            }
            //this will force the changed flag of the output pin to be set
            FStreamOut.Flush(true);
        }
コード例 #14
0
        //called when data for any output pin is requested
        public void Evaluate(int SpreadMax)
        {
            FTextureOut.ResizeAndDispose(SpreadMax, CreateTextureResource);
            FScaleOutput.SliceCount = SpreadMax;
            FSizeOutput.SliceCount  = SpreadMax;

            for (int i = 0; i < SpreadMax; i++)
            {
                var textureResource = FTextureOut[i];
                var info            = textureResource.Metadata;

                if (info.Width != FWidthIn[i] || info.Height != FHeightIn[i])
                {
                    textureResource.Dispose();
                    textureResource = CreateTextureResource(i);
                    info            = textureResource.Metadata;
                }

                if (info.Text != FTextInput[i] || info.Encoding != FCharEncoding[i].Index || info.Font != FFontInput[i].Name ||
                    info.Italic != FItalicInput[i] || info.Bold != FBoldInput[i] || info.Size != FSizeInput[i] ||
                    info.Color != FColorInput[i] || info.Brush != FBrushColor[i] || info.ShowBrush != FShowBrush[i] ||
                    info.HAlign != FHorizontalAlignInput[i].Index || info.VAlign != FVerticalAlignInput[i].Index ||
                    info.RenderMode != FTextRenderingModeInput[i].Index || info.Normalize != FNormalizeInput[i].Index)
                {
                    info.Text       = FTextInput[i];
                    info.Encoding   = FCharEncoding[i].Index;
                    info.Font       = FFontInput[i].Name;
                    info.Italic     = FItalicInput[i];
                    info.Bold       = FBoldInput[i];
                    info.Size       = FSizeInput[i];
                    info.Color      = FColorInput[i];
                    info.Brush      = FBrushColor[i];
                    info.ShowBrush  = FShowBrush[i];
                    info.HAlign     = FHorizontalAlignInput[i].Index;
                    info.VAlign     = FVerticalAlignInput[i].Index;
                    info.RenderMode = FTextRenderingModeInput[i].Index;
                    info.Normalize  = FNormalizeInput[i].Index;

                    textureResource.NeedsUpdate = true;
                }
                else
                {
                    textureResource.NeedsUpdate = false;
                }

                FTextureOut[i] = textureResource;
            }
        }
コード例 #15
0
        public void Evaluate(int spreadMax)
        {
            if (FStreamIn.SliceCount == 0 || FStreamIn[0] == null || FStreamIn[0].Length == 0)
            {
                spreadMax = 0;
            }
            else
            {
                spreadMax = FStreamIn.SliceCount;
            }

            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());
            for (int i = 0; i < spreadMax; i++)
            {
                var inputStream  = FStreamIn[i];
                var outputStream = FStreamOut[i];

                inputStream.Position  = 0;
                outputStream.Position = 0;

                FStreamOut[i].SetLength(0);
                var compressedDataSize = (int)inputStream.Length;

                IntPtr contentPtr     = Marshal.AllocHGlobal(compressedDataSize);
                byte[] compressedData = new byte[compressedDataSize];
                inputStream.Read(compressedData, 0, compressedDataSize);
                Marshal.Copy(compressedData, 0, contentPtr, compressedDataSize);

                fixed(byte *bptr = &compressedData[0])
                {
                    SnappyCodec.GetUncompressedLength(bptr, compressedDataSize, ref this.uncompressedSize);
                    IntPtr uncompressedDataPointer = Marshal.AllocHGlobal(this.uncompressedSize);

                    SnappyCodec.Uncompress(bptr, compressedDataSize, (byte *)uncompressedDataPointer, ref this.uncompressedSize);

                    this.uncompressedFrameData = new byte[this.uncompressedSize];
                    Marshal.Copy((IntPtr)uncompressedDataPointer, this.uncompressedFrameData, 0, this.uncompressedSize);
                    outputStream.Write(this.uncompressedFrameData, 0, this.uncompressedSize);

                    Marshal.FreeHGlobal(uncompressedDataPointer);
                }

                Marshal.FreeHGlobal(contentPtr);
            }
            FStreamOut.Flush(true);
        }
コード例 #16
0
        public void Evaluate(int spreadMax)
        {
            if (!FInput.IsChanged)
            {
                return;
            }

            FOutput.ResizeAndDispose(spreadMax, () => new MemoryStream());
            for (int i = 0; i < spreadMax; i++)
            {
                var outputArray  = Convert.FromBase64String(FInput[i]);
                var outputStream = FOutput[i];
                outputStream.Position = 0;
                outputStream.SetLength(outputArray.Length);
                outputStream.Write(outputArray, 0, outputArray.Length);
            }
        }
コード例 #17
0
        public void Evaluate(int spreadMax)
        {
            if (FStreamIn.SliceCount == 0 || FStreamIn[0] == null || FStreamIn[0].Length == 0)
            {
                spreadMax = 0;
            }
            else
            {
                spreadMax = FStreamIn.SliceCount;
            }

            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());

            for (int i = 0; i < spreadMax; i++)
            {
                var inputStream  = FStreamIn[i];
                var outputStream = FStreamOut[i];

                inputStream.Position  = 0;
                outputStream.Position = 0;

                FStreamOut[i].SetLength(0);
                var length = (int)inputStream.Length;

                IntPtr contentPtr = Marshal.AllocHGlobal(length);
                byte[] memory     = new byte[length];
                inputStream.Read(memory, 0, length);
                Marshal.Copy(memory, 0, contentPtr, length);

                int maxCompressedLength = SnappyCodec.GetMaximumCompressedLength(length);
                this.compressedFrameData = new byte[maxCompressedLength];

                fixed(byte *bptr = &this.compressedFrameData[0])
                {
                    this.compressedSize = maxCompressedLength;
                    SnappyCodec.Compress((byte *)contentPtr, length, bptr, ref this.compressedSize);
                    byte[] output = new byte[this.compressedSize];
                    Marshal.Copy((IntPtr)bptr, output, 0, this.compressedSize);
                    outputStream.Write(this.compressedFrameData, 0, this.compressedSize);
                }

                Marshal.FreeHGlobal(contentPtr);
            }
            FStreamOut.Flush(true);
        }
コード例 #18
0
        //called when data for any output pin is requested
        public void Evaluate(int SpreadMax)
        {
            SpreadMax = (int)Math.Ceiling(FInput.SliceCount / (StripLength[0] * 8.0));
            FOutput.ResizeAndDispose(SpreadMax, () => new MemoryStream(GetLength()));

            for (int teensy = 0; teensy < SpreadMax; teensy++)
            {
                var output = FOutput[teensy] ?? new MemoryStream(GetLength());
                output.SetLength(GetLength());
                output.Seek(0, SeekOrigin.Begin);

                for (int x = 0; x < StripLength[0]; x++)
                {
                    for (byte color = 0; color < 3; color++)
                    {
                        byte   mask       = 0;
                        byte[] components = new byte[8];

                        for (int stripe = 0; stripe < 8; stripe++)
                        {
                            var led = FInput[teensy * 8 * StripLength[0] + x + stripe * StripLength[0]];
                            components[stripe] = GetComponent(led, color);
                        }


                        byte[] pwm = new byte[8];

                        for (int bit = 0; bit < 8; bit++)
                        {
                            mask         = (byte)(1 << bit);
                            pwm[7 - bit] = 0;

                            for (byte pin = 0; pin < 8; pin++)
                            {
                                pwm[7 - bit] += (byte)(((components[pin] & mask) >> bit) << pin);                               // each byte contains 8 bits across all 8 pins. this way octows2811 can modulate the pwms superfast
                            }
                        }

                        output.Write(pwm, 0, 8);
                    }
                }
                FOutput[teensy] = output;
            }
        }
コード例 #19
0
        public void Evaluate(int SpreadMax)
        {
            if (OpenIn.Any(v => v) || CloseIn.Any(v => v))
            {
                DeviceIn.Sync();
                DeviceOut.ResizeAndDispose(DeviceIn.SliceCount, () => new HidDeviceWrap());
                for (int i = 0; i < DeviceOut.SliceCount; i++)
                {
                    if (OpenIn[i])
                    {
                        if (DeviceOut[i] == null)
                        {
                            DeviceOut[i] = new HidDeviceWrap();
                        }
                        if (DeviceOut[i].Device == null)
                        {
                            DeviceOut[i].Device = DeviceIn[i];
                            DeviceOut[i].Initialize();
                        }
                        else
                        {
                            DeviceOut[i].Open();
                        }
                    }

                    if (CloseIn[i] && DeviceOut[i] != null && DeviceOut[i].Opened)
                    {
                        DeviceOut[i].Close();
                        DeviceOut[i].Dispose();
                        DeviceOut[i] = null;
                    }
                }
                DeviceOut.Stream.IsChanged = true;
                DeviceOut.Flush(true);
            }

            if (_changeRef != HidChange.GlobalChangeCounter)
            {
                _changeRef = HidChange.GlobalChangeCounter;
                DeviceOut.Stream.IsChanged = true;
                DeviceOut.Flush(true);
            }
        }
コード例 #20
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            if (this.FFilenameIn.IsChanged || FReloadFile[0])
            {
                string path = this.FFilenameIn[0];
                if (File.Exists(path))
                {
                    this.FReader = new StreamReader(path);
                }
                FLength[0] = this.FReader.BaseStream.Length;
            }

            if (this.FDoRead[0] == true && this.FReader != null)
            {
                FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());
                var inputStream = FReader.BaseStream;

                for (int i = 0; i < spreadMax; i++)
                {
                    var outputStream   = FStreamOut[i];
                    var pos            = FPositionIn[i] % inputStream.Length;
                    var count          = Math.Max(FCountIn[i], 0);
                    var numBytesToCopy = Math.Min(inputStream.Length - pos, count);

                    inputStream.Position  = pos;
                    outputStream.Position = 0;

                    outputStream.SetLength(numBytesToCopy);

                    while (numBytesToCopy > 0)
                    {
                        var chunkSize    = (int)Math.Min(numBytesToCopy, FBuffer.Length);
                        var numBytesRead = inputStream.Read(FBuffer, 0, chunkSize);
                        if (numBytesRead == 0)
                        {
                            break;
                        }
                        outputStream.Write(FBuffer, 0, numBytesRead);
                        numBytesToCopy -= numBytesRead;
                    }
                }
            }
        }
コード例 #21
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());
            for (int i = 0; i < spreadMax; i++)
            {
                if (FMessageIn.IsChanged || FFacility.IsChanged || FLevel.IsChanged)
                {
                    byte[] message = ConstructMessage(FLevel[i], FFacility[i], FMessageIn[i]);

                    Stream outputStream = FStreamOut[i];

                    outputStream.Position = 0;
                    outputStream.SetLength(message.Length);
                    outputStream.Write(message, 0, message.Length);
                }
            }
            //this will force the changed flag of the output pin to be set
            FStreamOut.Flush(true);
        }
コード例 #22
0
        public void Evaluate(int SpreadMax)
        {
            if (FInput.IsConnected)
            {
                FText.SliceCount = SpreadMax;
                FBinary.ResizeAndDispose(FInput.SliceCount, () => new MemoryStream());
                FType.SliceCount = SpreadMax;

                for (int i = 0; i < SpreadMax; i++)
                {
                    if (FInput[i] is ClientMessage)
                    {
                        var cm = (ClientMessage)FInput[i];
                        FText[i]            = cm.Text;
                        FBinary[i].Position = 0;
                        FBinary[i].SetLength(cm.Raw.Length);
                        FBinary[i].Write(cm.Raw, 0, cm.Raw.Length);
                        FType[i] = cm.Type.ToString();
                    }
                }
            }
        }
コード例 #23
0
ファイル: Syslog.cs プロジェクト: vnmone/vvvv-sdk
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            spreadMax = Max(FMessageIn.SliceCount,
                            FFacility.SliceCount,
                            FSeverity.SliceCount,
                            FHostname.SliceCount,
                            FAppName.SliceCount,
                            FProcId.SliceCount,
                            FMsgId.SliceCount,
                            FStructuredDataName.SliceCount,
                            FStructuredDataValue.SliceCount);

            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());

            for (int i = 0; i < spreadMax; i++)
            {
                if (FMessageIn.IsChanged ||
                    FFacility.IsChanged ||
                    FSeverity.IsChanged ||
                    FHostname.IsChanged ||
                    FAppName.IsChanged ||
                    FProcId.IsChanged ||
                    FMsgId.IsChanged /*||
                                      * FStructuredData.IsChanged*/)
                {
                    //create msg
                    SyslogMessage msg = Create(FFacility[i], FSeverity[i], FMessageIn[i]);

                    // add properties
                    if (FHostname[i] != string.Empty)
                    {
                        msg.HostName = FHostname[i];
                    }
                    if (FAppName[i] != string.Empty)
                    {
                        msg.AppName = FAppName[i];
                    }
                    if (FProcId[i] != string.Empty)
                    {
                        msg.ProcessID = FProcId[i];
                    }
                    if (FMsgId[i] != string.Empty)
                    {
                        msg.MessageID = FMsgId[i];
                    }

                    // add structured Data
                    List <StructuredDataElement> sd  = new List <StructuredDataElement>();
                    StructuredDataElement        sde = new StructuredDataElement();
                    sde.ID = FSDID[0] + "@" + FEID[0];  // set id according to rfc5424 ... the enterprise ID is a wildcard anyway, since one is not registered at the IANA

                    for (int s = 0; s < FStructuredDataName[i].SliceCount; s++)
                    {
                        sde.Properties.Add(FStructuredDataName[i][s], FStructuredDataValue[i][s]);
                    }
                    sd.Add(sde);
                    msg.StructuredData = sd;

                    // convert to stream
                    byte[] byteMessage  = System.Text.Encoding.ASCII.GetBytes(msg.ToIetfSyslogString());
                    Stream outputStream = FStreamOut[i];

                    // write out
                    outputStream.Position = 0;
                    outputStream.SetLength(byteMessage.Length);
                    outputStream.Write(byteMessage, 0, byteMessage.Length);
                }
            }
            //this will force the changed flag of the output pin to be set
            FStreamOut.Flush(true);
        }
コード例 #24
0
        public void Evaluate(int spreadmax)
        {
            if (FInClient.IsConnected)
            {
                if (FClient == null && FInClient[0] != null)
                {
                    FClient = FInClient[0];
                    FClient.MqttMsgPublishReceived += FClient_MqttMsgPublishReceived;
                    FClient.MqttMsgSubscribed      += FClient_MqttMsgSubscribed;
                    FClient.MqttMsgUnsubscribed    += FClient_MqttMsgUnsubscribed;
                }
                if (FClient != null && FInClient[0] == null)
                {
                    FClient.MqttMsgPublishReceived -= FClient_MqttMsgPublishReceived;
                    FClient.MqttMsgSubscribed      -= FClient_MqttMsgSubscribed;
                    FClient.MqttMsgUnsubscribed    -= FClient_MqttMsgUnsubscribed;
                    FClient = null;
                }

                if (FClient != null && FClient.IsConnected)
                {
                    HashSet <Tuple <string, QOS> > currentSubscriptions = new HashSet <Tuple <string, QOS> >();
                    List <Tuple <string, QOS> >    newSubscriptions     = new List <Tuple <string, QOS> >();
                    for (int i = 0; i < spreadmax; i++)
                    {
                        var tup = new Tuple <string, QOS>(FInTopic[i], FInQoS[i]);
                        currentSubscriptions.Add(tup);

                        if (!FSubscriptions.Remove(tup))
                        {
                            newSubscriptions.Add(tup);
                        }
                    }

                    #region unsubscribe
                    try
                    {
                        if (FSubscriptions.Count > 0)
                        {
                            foreach (var tuple in FSubscriptions)
                            {
                                var unsubscribeId = FClient.Unsubscribe(new string[] { tuple.Item1 });
                                FUnsubscribeStatus.Add(unsubscribeId, tuple);
                            }
                        }
                        FSubscriptions = new HashSet <Tuple <string, QOS> >(currentSubscriptions);
                    }
                    catch (Exception e)
                    {
                        FLogger.Log(e);
                        foreach (var s in currentSubscriptions)
                        {
                            FSubscriptions.Add(s);
                        }
                    }
                    #endregion unsubscribe

                    #region subscribe
                    foreach (var subs in newSubscriptions)
                    {
                        try
                        {
                            var subscribeId = FClient.Subscribe(new string[] { subs.Item1 }, new byte[] { (byte)subs.Item2 });
                            FSubscribeStatus.Add(subscribeId, subs);
                        }
                        catch
                        {
                            FLogger.Log(LogType.Warning, string.Format("couldn't subscribe to {0} with qos {1}", subs.Item1, subs.Item2));
                        }
                    }
                    #endregion subscribe
                }
            }

            //Writing incoming bytes into the Slices of the Output Stream
            var messages = FPacketQueue.Select(x => x.Message);
            FOutMessage.ResizeAndDispose(messages.Count(), () => new MemoryComStream());

            if (messages.Count() > 0)
            {
                int k = 0;
                foreach (var m in messages)
                {
                    FOutMessage[k].Write(m, 0, m.Length);
                    k++;
                }
            }

            FOutTopic.AssignFrom(FPacketQueue.Select(x => x.Topic).ToArray());
            FOutQoS.AssignFrom(FPacketQueue.Select(x => (QOS)x.QosLevel));
            FOutIsRetained.AssignFrom(FPacketQueue.Select(x => x.Retain));
            FOutOnData[0] = FPacketQueue.Count > 0;
            FPacketQueue.Clear();

            if (FMessageStatusQueue.Count > 0)
            {
                FOutMessageStatus.AssignFrom(FMessageStatusQueue.ToArray());
                FMessageStatusQueue.Clear();
            }

            FOutMessage.Flush();
        }
コード例 #25
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            FResponse.ResizeAndDispose(spreadMax, () => new MemoryStream());
            FHeader.SliceCount  = spreadMax;
            FStatus.SliceCount  = spreadMax;
            FFailed.SliceCount  = spreadMax;
            FSuccess.SliceCount = spreadMax;
            for (int i = 0; i < spreadMax; i++)
            {
                if (FRefresh[i])
                {
                    try
                    {
                        Uri            url     = new Uri(FURL[i]);
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                        request.Method = FProtocol[i].ToString();
                        if (!string.IsNullOrEmpty(FInHeader[i]))
                        {
                            request.Headers.Add(FInHeader[i]);
                        }
                        request.UserAgent   = "vvvv";
                        request.Credentials = System.Net.CredentialCache.DefaultCredentials;

                        byte[] buffer    = new byte[1024];
                        int    bytesRead = 0;
                        if (((int)FProtocol[i] == (int)HTTPProtocol.POST) || ((int)FProtocol[i] == (int)HTTPProtocol.PUT))
                        {
                            request.ContentType   = FMimeType[i].Name;
                            request.ContentLength = FContent[i].Length;
                            using (Stream reqstr = request.GetRequestStream())
                            {
                                while ((bytesRead = FContent[i].Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    reqstr.Write(buffer, 0, bytesRead);
                                }
                            }
                        }

                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            FStatus[i] = string.Format("{0} {1} {2} {3}", url.Scheme.ToUpper(), response.ProtocolVersion, (int)(response.StatusCode), response.StatusDescription);
                            FHeader[i] = response.Headers.ToString();

                            using (Stream respstr = response.GetResponseStream())
                            {
                                if (response.ContentLength >= 0)
                                {
                                    FResponse[i].SetLength(response.ContentLength);
                                    while ((bytesRead = respstr.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        FResponse[i].Write(buffer, 0, bytesRead);
                                    }
                                }
                                else
                                {
                                    int bytesTotal = 0;
                                    FResponse[i].SetLength(0);
                                    while ((bytesRead = respstr.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        bytesTotal += bytesRead;
                                        FResponse[i].SetLength(bytesTotal);
                                        FResponse[i].Write(buffer, 0, bytesRead);
                                    }
                                }
                            }
                            FResponse.Flush(true);
                            FFailed[i]  = false;
                            FSuccess[i] = true;
                        }
                        catch (WebException we)
                        {
                            if (we.Status == WebExceptionStatus.ProtocolError)
                            {
                                var weResp = (HttpWebResponse)we.Response;
                                FStatus[i] = string.Format("{0} {1} {2} {3}", url.Scheme.ToUpper(), weResp.ProtocolVersion, (int)(weResp.StatusCode), weResp.StatusDescription);
                            }
                            else
                            {
                                FStatus[i] = we.Status.ToString();
                            }
                            FHeader[i] = string.Empty;
                            FContent[i].SetLength(0);
                            FFailed[i]  = true;
                            FSuccess[i] = false;
                        }
                    }
                    catch (Exception e)
                    {
                        FLogger.Log(e);
                        FStatus[i] = e.Message;
                        FHeader[i] = string.Empty;
                        FContent[i].SetLength(0);
                        FFailed[i]  = true;
                        FSuccess[i] = false;
                    }
                }
            }
        }
コード例 #26
0
        //called when data for any output pin is requested
        public void Evaluate(int SpreadMax)
        {
            SpreadMax = FInputBaseURL.SliceCount;

            // Set the slice counts of our outputs.
            FOutputHeader.SliceCount  = SpreadMax;
            FOutputSuccess.SliceCount = SpreadMax;
            FOutputStatus.SliceCount  = SpreadMax;
            FRAWOutputResponse.ResizeAndDispose(SpreadMax, () => new MemoryStream());

            // Set slice count for Task and cancelation Tokens.
            FTasks.SliceCount = SpreadMax;
            FCts.SliceCount   = SpreadMax;
            ct.SliceCount     = SpreadMax;
            TaskCount         = SpreadMax;

            // Set Spread count for specific objects
            client.SliceCount   = SpreadMax;
            request.SliceCount  = SpreadMax;
            response.SliceCount = SpreadMax;

            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            //FRAWOutputResponse.ResizeAndDispose(SpreadMax, () => new MemoryStream());

            // start doing stuff foreach spread item
            for (int i = 0; i < SpreadMax; i++)
            {
                // store i to a new variable so it won't change when tasks are running over longer period.
                // this is important to asign results to the right slice position.
                int index = i;

                if (FInputCancel[index])
                {
                    CancelRunningTasks(index);
                }

                if (FInputExecute[i])
                {
                    // Clear Fields
                    //FOutputResponse[index] = "";
                    FOutputHeader[index]      = "";
                    FOutputSuccess[index]     = false;
                    FOutputStatus[index]      = "";
                    FRAWOutputResponse[index] = null;

                    // Let's first cancel all running tasks (if any).
                    CancelRunningTasks(index);

                    // Create a new task cancellation source object.
                    FCts[index] = new CancellationTokenSource();
                    // Retrieve the cancellation token from it which we'll use for
                    // the new tasks we setup up now.
                    ct[index] = FCts[index].Token;

                    FTasks[index] = Task.Factory.StartNew(() =>
                    {
                        // Should a cancellation be requested throw the task
                        // canceled exception.
                        ct[index].ThrowIfCancellationRequested();


                        // >>> Start the Work
                        try
                        {
                            var AddParameter = false;
                            var AddBody      = false;

                            //##################
                            //## Setup Client ##
                            // Setup RestClient
                            client[index]         = new RestClient();
                            client[index].BaseUrl = new Uri(FInputBaseURL[index]);
                            client[index].ClearHandlers();

                            //####################
                            //## Authentication ##
                            //client[index].Authenticator = new OAuthAuthenticator();
                            if (FInputAuthentication[index] != null)
                            {
                                FLogger.Log(LogType.Debug, "Auth!");
                                client[index].Authenticator = FInputAuthentication[index];                                //new HttpBasicAuthenticator(FInputUsername[index], FInputPassword[index]);
                            }
                            FOutputStatus[index] = getTimestamp() + " - Client Setup.\n";


                            //###################
                            //## Setup Request ##
                            request[index]        = new RestRequest();
                            request[index].Method = FInputHttpMethod[index];                             // REST method eg. POST, GET, DELETE etc.
                            //request[index].Parameters.Clear();


                            //#################
                            //## Adding Body ##
                            if (FInputBody[index].Data != null)
                            {
                                FLogger.Log(LogType.Message, "Body length: " + FInputBody[index].Data.Length);
                                AddBody = true;
                                request[index].AddParameter(FInputBody[index].Type, FInputBody[index].Data, ParameterType.RequestBody);
                            }


                            //#################
                            //## Adding File ##
                            var FileData = FInputFileUpload[index];
                            for (int ii = 0; ii < FileData.SliceCount; ii++)
                            {
                                if (FileData[ii].FileContent != null)
                                {
                                    FLogger.Log(LogType.Message, "File Uplaod! Name:" + FileData[ii].FileName + " File Type:" + FileData[ii].FileType);
                                    //request[index].AddFile(FileData[ii].FileName, FileData[ii].FileContent, FileData[ii].FileName, FileData[ii].FileType);
                                    request[index].AddFile("name", BytestreamToArray(FileData[ii].FileContent), "name");
                                    //request[index].AddParameter("", BytestreamToArray(FileData[ii].FileContent), ParameterType.RequestBody); // tried to overcome forced multipart behaviert.
                                }
                            }

                            //request[index].Parameters.Clear();

                            //#######################
                            //## Adding Parameters ##
                            var Paramters = FInputKeyValueParameter[index];
                            for (int ii = 0; ii < Paramters.SliceCount; ii++)
                            {
                                if (Paramters[ii].Key != null)
                                {
                                    FLogger.Log(LogType.Message, "Parameter Key: " + Paramters[ii].Key + "  Value: " + Paramters[ii].Value);
                                    AddParameter = true;
                                    request[index].AddParameter(Paramters[ii].Key, Paramters[ii].Value);                                     // works!
                                }
                            }


                            //###################
                            //## Adding Header ##
                            var Headers = FInputHeader[index];
                            for (int ii = 0; ii < Headers.SliceCount; ii++)
                            {
                                if (Headers[ii].HeaderName != null)
                                {
                                    FLogger.Log(LogType.Message, "Header Name: " + Headers[ii].HeaderName + "  Value: " + Headers[ii].HeaderValue);
                                    request[index].AddHeader(Headers[ii].HeaderName, Headers[ii].HeaderValue);
                                    //request[index].AddHeader(Headers[ii].HeaderName, Headers[ii].HeaderValue);
                                }
                            }

                            //##################################
                            //## Check for Body and Parameter ##
                            /* Adding Parameter and Body at once is not possible. See also: https://groups.google.com/forum/#!topic/restsharp/3NVVMridDJ0 */
                            if (AddParameter && AddBody)
                            {
                                var warning = "\nSorry. You can't add Body and Parameter at once due to limitations of the used library. \n Body data will be ignored.\n\n";
                                FLogger.Log(LogType.Error, "HTTP REST Node: " + warning);
                                FOutputStatus[index] += warning;
                            }

                            //request[index].Parameters.Clear();

                            string infor = request[index].Files.ToString();
                            FLogger.Log(LogType.Error, "FileCount: " + request[index].Files.Count);

                            //#####################
                            //## Execute Request ##
                            response[index] = client[index].Execute(request[index]);                            // TODO Add cancleation token here?
                        }
                        catch (Exception e)
                        {
                            FLogger.Log(LogType.Debug, "HTTP-REST Exception:" + e);
                            FOutputStatus[index] += e;
                        }
                        // <<< Done the Work



                        // Return the results
                        return(new { RESTResponse = response[index] });
                    }, ct[index]).ContinueWith(t =>
                    {
                        //
                        // Assign results to the output of vvvv.
                        //

                        // Get the response Body.
                        var result = t.Result.RESTResponse;

                        FRAWOutputResponse[index] = new MemoryStream(result.RawBytes);

                        // get Complete Header
                        int FHeaderItems = result.Headers.Count;
                        if (FHeaderItems > 0)
                        {
                            FOutputHeader[index] = "";
                            for (int j = 0; j < FHeaderItems; j++)
                            {
                                FOutputHeader[index] += j.ToString() + " " + result.Headers[j] + "\n";
                            }
                        }

                        FOutputStatus[index] += getTimestamp() + " - Response.\n";
                        FOutputStatus[index] += "ResponseStatus:	"+ result.ResponseStatus + "\n";
                        FOutputStatus[index] += "StatusDescription:	" + result.StatusDescription + "\n";
                        FOutputStatus[index] += "StatusCode:	"+ result.StatusCode.ToString() + "\n";
                        FOutputStatus[index] += "Request:		"+ result.Request.RequestFormat + "\n";
                        FOutputStatus[index] += "ResponseUri:	"+ result.ResponseUri + "\n";

                        if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode == System.Net.HttpStatusCode.Created)                         // ToString() == "OK" || t.Result.RESTResponse.StatusCode.ToString() == "Created")
                        {
                            FOutputSuccess[index] = true;
                        }
                        else
                        {
                            FOutputSuccess[index] = false;
                        }
                    }, ct[index],
                                               // Here we can specify some options under which circumstances the
                                               // continuation should run. In this case we only want it to run if
                                               // the task wasn't cancelled before.
                                               TaskContinuationOptions.OnlyOnRanToCompletion,
                                               // This way we tell the continuation to run on the main thread of vvvv.
                                               TaskScheduler.FromCurrentSynchronizationContext()
                                               );
                }
            }
        }
コード例 #27
0
        public void Evaluate(int spreadMax)
        {
            DcdStateOut.SliceCount   = spreadMax;
            CtsStateOut.SliceCount   = spreadMax;
            DsrStateOut.SliceCount   = spreadMax;
            RiStateOut.SliceCount    = spreadMax;
            BreakStateOut.SliceCount = spreadMax;

            if (UpdatePortListIn.IsChanged && UpdatePortListIn[0])
            {
                GlobalEnumManager.UpdatePortList();
            }

            FPorts.Resize(spreadMax, CreatePort, DestroyPort);
            DataOut.ResizeAndDispose(spreadMax, () => new MemoryStream());

            for (int i = 0; i < spreadMax; i++)
            {
                var port = FPorts[i];
                // Get the in and output streams
                var dataIn  = DataIn[i];
                var dataOut = DataOut[i];
                // Set stream positions back to the beginning
                dataIn.Seek(0, SeekOrigin.Begin);
                dataOut.Seek(0, SeekOrigin.Begin);

                try
                {
                    if (EnabledIn[i])
                    {
                        // Try to configure the port
                        TryConfigurePort(port, i);

                        // Open the port
                        if (!port.IsOpen)
                        {
                            port.Open();
                            SetStates(i);
                        }

                        // Can only be set if port is open
                        try
                        {
                            TrySetBreakState(port, BreakStateIn[i]);
                        }
                        catch (Exception e)
                        {
                            FLogger.Log(e);
                        }

                        // Write data to the port
                        var totalBytesToWrite = dataIn.Length;
                        if (totalBytesToWrite > 0 && DoSendIn[i])
                        {
                            var buffer = new byte[1024];
                            while (totalBytesToWrite > 0)
                            {
                                var bytesToWrite = (int)Math.Min(buffer.Length, totalBytesToWrite);
                                var bytesRead    = dataIn.Read(buffer, 0, bytesToWrite);
                                port.Write(buffer, 0, bytesRead);
                                totalBytesToWrite -= bytesRead;
                            }
                        }

                        // Read data from the port
                        var totalBytesToRead = port.BytesToRead;
                        if (totalBytesToRead > 0)
                        {
                            dataOut.SetLength(totalBytesToRead);
                            var buffer = new byte[1024];
                            while (totalBytesToRead > 0)
                            {
                                var bytesToRead = Math.Min(buffer.Length, totalBytesToRead);
                                var bytesRead   = port.Read(buffer, 0, bytesToRead);
                                dataOut.Write(buffer, 0, bytesRead);
                                totalBytesToRead -= bytesRead;
                            }
                            // Marks the pin as changed
                            DataOut[i] = dataOut;
                            // Set the OnData flag
                            OnDataOut[i] = true;
                        }
                        else
                        {
                            // Clear output
                            if (dataOut.Length > 0)
                            {
                                dataOut.SetLength(0);
                                // Marks the pin as changed
                                DataOut[i] = dataOut;
                                // Reset the OnData flag
                                OnDataOut[i] = false;
                            }
                        }
                    }
                    else
                    {
                        // Close the port
                        if (port.IsOpen)
                        {
                            port.Close();
                            UnsetStates(i);
                        }
                        // Clear output
                        if (dataOut.Length > 0)
                        {
                            dataOut.SetLength(0);
                            // Marks the pin as changed
                            DataOut[i] = dataOut;
                            // Reset the OnData flag
                            OnDataOut[i] = false;
                        }
                    }

                    // Read connection state
                    ConnectedOut[i] = port.IsOpen;
                }
                catch (IOException e)
                {
                    // Reset outputs
                    DataOut[i].SetLength(0);
                    UnsetStates(i);
                    ConnectedOut[i] = false;
                    // Log the exception
                    FLogger.Log(e);
                }
            }
        }
コード例 #28
0
        //called when data for any output pin is requested
        public void Evaluate(int spreadMax)
        {
            //ResizeAndDispose will adjust the spread length and thereby call
            //the given constructor function for new slices and Dispose on old
            //slices.
            spreadMax = FDataIn.SliceCount;

            FStreamOut.ResizeAndDispose(spreadMax, () => new MemoryStream());
            FPositionOut.SliceCount = spreadMax;

            while (this.FStatus.Count < spreadMax)
            {
                this.FStatus.Add(new Status());
            }
            for (int i = 0; i < spreadMax; i++)
            {
                var outputStream = FStreamOut[i];
                if (this.FResetIn[i])
                {
                    this.FStatus[i] = new Status();
                }
                var status = this.FStatus[i];

                outputStream.SetLength(0);

                if (FRequestPositionIn[i].SliceCount > 0)
                {
                    foreach (var requestPosition in FRequestPositionIn[i])
                    {
                        if (requestPosition < status.position)
                        {
                            status.position = requestPosition;
                        }
                    }
                }

                if (FSendIn[i])
                {
                    outputStream.Seek(0, SeekOrigin.Begin);
                    var dataLength = FDataIn[i].Length;
                    if (!status.beginSent)
                    {
                        this.WriteOTABegin(outputStream, FIDIn[i], (UInt32)dataLength);
                        status.beginSent = true;
                    }
                    else
                    {
                        if (status.position < dataLength)
                        {
                            for (int c = 0; c < FSpeedIn[i]; c++)
                            {
                                status.position = this.WriteOTAData(outputStream, FIDIn[i], FDataIn[i], status.position);
                                if (status.position >= FDataIn[i].Length)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    FPositionOut[i] = status.position;
                }

                FSizeOut[i] = (int)FDataIn[i].Length;
            }
            //this will force the changed flag of the output pin to be set
            FStreamOut.Flush(true);
        }
コード例 #29
0
        //called when data for any output pin is requested
        public void Evaluate(int SpreadMax)
        {
            FTextureOut.ResizeAndDispose(SpreadMax, CreateTextureResource);
            FBmpBuffer.ResizeAndDispose(SpreadMax, (t) => new Bitmap(FTextureOut[t].Metadata.Width, FTextureOut[t].Metadata.Height, PixelFormat.Format32bppArgb));
            FScaleOutput.SliceCount = SpreadMax;
            FSizeOutput.SliceCount  = SpreadMax;

            for (int i = 0; i < SpreadMax; i++)
            {
                var textureResource = FTextureOut[i];

                textureResource.NeedsUpdate = false;

                var info = textureResource.Metadata;
                if (info.Width != FWidthIn[i] || info.Height != FHeightIn[i])
                {
                    textureResource.Dispose();
                    textureResource             = CreateTextureResource(i);
                    textureResource.NeedsUpdate = true;

                    info = textureResource.Metadata;
                    FBmpBuffer[i].Dispose();
                    FBmpBuffer[i]          = new Bitmap(info.Width, info.Height, PixelFormat.Format32bppArgb);
                    info.PropertiesChanged = true;
                }

                info.Text       = FTextInput[i];
                info.Font       = FFontInput[i].Name;
                info.Italic     = FItalicInput[i];
                info.Bold       = FBoldInput[i];
                info.Size       = FSizeInput[i];
                info.Color      = FColorInput[i];
                info.Brush      = FBrushColor[i];
                info.ShowBrush  = FShowBrush[i];
                info.HAlign     = FHorizontalAlignInput[i].Index;
                info.VAlign     = FVerticalAlignInput[i].Index;
                info.RenderMode = FTextRenderingModeInput[i].Index;
                info.Normalize  = FNormalizeInput[i].Index;

                if (info.PropertiesChanged)
                {
                    info.PropertiesChanged      = false;
                    textureResource.NeedsUpdate = true;

                    Graphics  g     = Graphics.FromImage(FBmpBuffer[i]);
                    FontStyle style = FontStyle.Regular;
                    if (info.Italic)
                    {
                        style |= FontStyle.Italic;
                    }
                    if (info.Bold)
                    {
                        style |= FontStyle.Bold;
                    }
                    System.Drawing.Font objFont = new System.Drawing.Font(info.Font, info.Size, style, GraphicsUnit.Pixel);

                    string text = info.Text;

                    int          renderingMode = info.RenderMode;
                    RectangleF   layout        = new RectangleF(0, 0, 0, 0);
                    StringFormat format        = new StringFormat();
                    if (!string.IsNullOrEmpty(text))
                    {
                        switch (renderingMode)
                        {
                        case 0: text = text.Replace("\n", " ").Replace("\n", string.Empty); break;

                        case 1: break;

                        case 2: layout.Size = new SizeF(info.Width, info.Height); break;
                        }

                        format.LineAlignment = StringAlignment.Near;
                        switch (info.HAlign)
                        {
                        case 0: format.Alignment = StringAlignment.Near; break;

                        case 1:
                            format.Alignment = StringAlignment.Center;
                            layout.X         = info.Width / 2;
                            break;

                        case 2:
                            format.Alignment = StringAlignment.Far;
                            layout.X         = info.Width;
                            break;
                        }

                        switch (info.VAlign)
                        {
                        case 0: format.LineAlignment = StringAlignment.Near; break;

                        case 1:
                            format.LineAlignment = StringAlignment.Center;
                            layout.Y             = info.Height / 2;
                            break;

                        case 2:
                            format.LineAlignment = StringAlignment.Far;
                            layout.Y             = info.Height;
                            break;
                        }

                        SizeF size = g.MeasureString(text, objFont, layout.Size, format);
                        FSizeOutput[i] = new Vector2D(info.Width / size.Width, info.Height / size.Height);

                        float scx = 1; float scy = 1;
                        switch (info.Normalize)
                        {
                        case 0: break;

                        case 1: scx = info.Width / size.Width; break;

                        case 2: scy = info.Height / size.Height; break;

                        case 3:
                            scx = info.Width / size.Width;
                            scy = info.Height / size.Height;
                            break;
                        }
                        FScaleOutput[i] = new Vector2D(scx, scy);

                        g.TranslateTransform(layout.X, layout.Y);
                        g.ScaleTransform(scx, scy);
                        g.TranslateTransform(-layout.X, -layout.Y);

                        if (renderingMode == 2)
                        {
                            layout.Location = new PointF(0, 0);
                        }
                    }
                    else
                    {
                        FScaleOutput[i] = new Vector2D(0, 0);
                    }


                    RGBAColor tmpBrush = info.Color;
                    tmpBrush.A = 0;
                    Color brush = tmpBrush.Color;
                    if (info.ShowBrush)
                    {
                        brush = info.Brush.Color;
                    }
                    g.Clear(brush);
                    g.SmoothingMode     = SmoothingMode.AntiAlias;
                    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                    g.DrawString(text, objFont, new SolidBrush(info.Color.Color), layout, format);
                    g.Dispose();
                }
                FTextureOut[i] = textureResource;
            }
        }
コード例 #30
0
 public void OnImportsSatisfied()
 {
     Output.SliceCount = 0;
     Output.ResizeAndDispose(0, (int i) => new RingStream(BufferSizes[i]));
 }