예제 #1
0
 /// <summary>
 /// Perform the 'get' operation.
 /// </summary>
 /// <param name="line"></param>
 /// <returns></returns>
 public Commands.Result Get(out Rhino.Geometry.Line line)
 {
   IntPtr pThis = NonConstPointer();
   line = Rhino.Geometry.Line.Unset;
   int rc = UnsafeNativeMethods.RHC_RhinoGetLine2(pThis, ref line, IntPtr.Zero);
   return (Commands.Result)rc;
 }
  public static Rhino.Commands.Result ExportControlPoints(Rhino.RhinoDoc doc)
  {
    Rhino.DocObjects.ObjRef objref;
    var get_rc = Rhino.Input.RhinoGet.GetOneObject("Select curve", false, Rhino.DocObjects.ObjectType.Curve, out objref);
    if (get_rc != Rhino.Commands.Result.Success)
      return get_rc;
    var curve = objref.Curve();
    if (curve == null)
      return Rhino.Commands.Result.Failure;
    var nc = curve.ToNurbsCurve();

    var fd = new System.Windows.Forms.SaveFileDialog();
    fd.Filter = "Text Files | *.txt";
    fd.DefaultExt = "txt";
    if( fd.ShowDialog(Rhino.RhinoApp.MainWindow())!= System.Windows.Forms.DialogResult.OK)
      return Rhino.Commands.Result.Cancel;
    string path = fd.FileName;
    using( System.IO.StreamWriter sw = new System.IO.StreamWriter(path) )
    {
      foreach( var pt in nc.Points )
      {
        var loc = pt.Location;
        sw.WriteLine("{0} {1} {2}", loc.X, loc.Y, loc.Z);
      }
      sw.Close();
    }
    return Rhino.Commands.Result.Success;
  }
예제 #3
0
    public static Rhino.Commands.Result AddLine(Rhino.RhinoDoc doc)
    {
        Rhino.Input.Custom.GetPoint gp = new Rhino.Input.Custom.GetPoint();
        gp.SetCommandPrompt("Start of line");
        gp.Get();
        if (gp.CommandResult() != Rhino.Commands.Result.Success)
          return gp.CommandResult();

        Rhino.Geometry.Point3d pt_start = gp.Point();

        gp.SetCommandPrompt("End of line");
        gp.SetBasePoint(pt_start, false);
        gp.DrawLineFromPoint(pt_start, true);
        gp.Get();
        if (gp.CommandResult() != Rhino.Commands.Result.Success)
          return gp.CommandResult();

        Rhino.Geometry.Point3d pt_end = gp.Point();
        Rhino.Geometry.Vector3d v = pt_end - pt_start;
        if (v.IsTiny(Rhino.RhinoMath.ZeroTolerance))
          return Rhino.Commands.Result.Nothing;

        if (doc.Objects.AddLine(pt_start, pt_end) != Guid.Empty)
        {
          doc.Views.Redraw();
          return Rhino.Commands.Result.Success;
        }
        return Rhino.Commands.Result.Failure;
    }
예제 #4
0
  public static Rhino.Commands.Result ObjectColor(Rhino.RhinoDoc doc)
  {
    Rhino.DocObjects.ObjRef[] objRefs;
    Rhino.Commands.Result cmdResult = Rhino.Input.RhinoGet.GetMultipleObjects("Select objects to change color", false, Rhino.DocObjects.ObjectType.AnyObject, out objRefs);
    if (cmdResult != Rhino.Commands.Result.Success)
      return cmdResult;

    System.Drawing.Color color = System.Drawing.Color.Black;
    bool rc = Rhino.UI.Dialogs.ShowColorDialog(ref color);
    if (!rc)
      return Rhino.Commands.Result.Cancel;

    for (int i = 0; i < objRefs.Length; i++)
    {
      Rhino.DocObjects.RhinoObject obj = objRefs[i].Object();
      if (null == obj || obj.IsReference)
        continue;

      if (color != obj.Attributes.ObjectColor)
      {
        obj.Attributes.ObjectColor = color;
        obj.Attributes.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject;
        obj.CommitChanges();
      }
    }

    doc.Views.Redraw();

    return Rhino.Commands.Result.Success;
  }
예제 #5
0
 protected override Rhino.Commands.Result RunCommand(RhinoDoc doc, Rhino.Commands.RunMode mode)
 {
     // You don't have to override RunCommand if you don't need any user input. In
       // this case we want to get a key from the user. If you return something other
       // than Success, the selection is canceled
       return Rhino.Input.RhinoGet.GetString("key", true, ref m_key);
 }
        protected override Result RunCommand(Rhino.RhinoDoc doc, RunMode mode)
        {
            // TODO: start here modifying the behaviour of your command.
              // ---
              RhinoApp.WriteLine ("The {0} command will add a line right now.", EnglishName);

              Point3d pt0;
              using (GetPoint getPointAction = new GetPoint ()) {
            getPointAction.SetCommandPrompt ("Please select the start point");
            if (getPointAction.Get () != GetResult.Point) {
              RhinoApp.WriteLine ("No start point was selected.");
              return getPointAction.CommandResult ();
            }
            pt0 = getPointAction.Point ();
              }

              Point3d pt1;
              using (GetPoint getPointAction = new GetPoint ()) {
            getPointAction.SetCommandPrompt ("Please select the end point");
            getPointAction.SetBasePoint (pt0, true);
            getPointAction.DrawLineFromPoint (pt0, true);
            if (getPointAction.Get () != GetResult.Point) {
              RhinoApp.WriteLine ("No end point was selected.");
              return getPointAction.CommandResult ();
            }
            pt1 = getPointAction.Point ();
              }

              doc.Objects.AddLine (pt0, pt1);
              doc.Views.Redraw ();
              RhinoApp.WriteLine ("The {0} command added one line to the document.", EnglishName);

              return Result.Success;
        }
    /// <summary>
    /// Rhino calls this function to remake objects when inputs have changed.  
    /// </summary>
    protected override bool ReplayHistory(Rhino.DocObjects.ReplayHistoryData replay)
    {
      Rhino.DocObjects.ObjRef objref = null;
      int segmentCount = 0;
      int pointCount = 0;

      if (!ReadHistory(replay, ref objref, ref segmentCount, ref pointCount))
        return false;

      Rhino.Geometry.Curve curve = objref.Curve();
      if (null == curve)
        return false;

      if (pointCount != replay.Results.Length)
        return false;

      Rhino.Geometry.Point3d[] points;
      curve.DivideByCount(segmentCount, true, out points);
      if (null == points)
        return false;

      for (int i = 0; i < points.Length; i++)
        replay.Results[i].UpdateToPoint(points[i], null);

      return true;
    }
예제 #8
0
  public static Rhino.Commands.Result MoveCPlane(Rhino.RhinoDoc doc)
  {
    Rhino.Display.RhinoView view = doc.Views.ActiveView;
    if (view == null)
      return Rhino.Commands.Result.Failure;

    Rhino.DocObjects.ConstructionPlane cplane = view.ActiveViewport.GetConstructionPlane();
    Point3d origin = cplane.Plane.Origin;

    MoveCPlanePoint gp = new MoveCPlanePoint(cplane);
    gp.SetCommandPrompt("CPlane origin");
    gp.SetBasePoint(origin, true);
    gp.DrawLineFromPoint(origin, true);
    gp.Get();

    if (gp.CommandResult() != Rhino.Commands.Result.Success)
      return gp.CommandResult();

    Point3d point = gp.Point();
    Vector3d v = origin - point;
    if (v.IsTiny())
      return Rhino.Commands.Result.Nothing;

    Plane pl = cplane.Plane;
    pl.Origin = point;
    cplane.Plane = pl;
    view.ActiveViewport.SetConstructionPlane(cplane);
    view.Redraw();
    return Rhino.Commands.Result.Success;
  }
  public static Rhino.Commands.Result AddLinearDimension2(Rhino.RhinoDoc doc)
  {
    Point3d origin = new Point3d(1,1,0);
    Point3d offset = new Point3d(11,1,0);
    Point3d pt = new Point3d((offset.X-origin.X)/2,3,0);

    Plane plane = Plane.WorldXY;
    plane.Origin = origin;

    double u,v;
    plane.ClosestParameter(origin, out u, out v);
    Point2d ext1 = new Point2d(u, v);

    plane.ClosestParameter(offset, out u, out v);
    Point2d ext2 = new Point2d(u, v);

    plane.ClosestParameter(pt, out u, out v);
    Point2d linePt = new Point2d(u, v);

    LinearDimension dimension = new LinearDimension(plane, ext1, ext2, linePt);
    if (doc.Objects.AddLinearDimension(dimension) != Guid.Empty)
    {
      doc.Views.Redraw();
      return Rhino.Commands.Result.Success;
    }
    return Rhino.Commands.Result.Failure;
  }
예제 #10
0
    public static Rhino.Commands.Result AddMesh(Rhino.RhinoDoc doc)
    {
        Rhino.Geometry.Mesh mesh = new Rhino.Geometry.Mesh();
        mesh.Vertices.Add(0.0, 0.0, 1.0); //0
        mesh.Vertices.Add(1.0, 0.0, 1.0); //1
        mesh.Vertices.Add(2.0, 0.0, 1.0); //2
        mesh.Vertices.Add(3.0, 0.0, 0.0); //3
        mesh.Vertices.Add(0.0, 1.0, 1.0); //4
        mesh.Vertices.Add(1.0, 1.0, 2.0); //5
        mesh.Vertices.Add(2.0, 1.0, 1.0); //6
        mesh.Vertices.Add(3.0, 1.0, 0.0); //7
        mesh.Vertices.Add(0.0, 2.0, 1.0); //8
        mesh.Vertices.Add(1.0, 2.0, 1.0); //9
        mesh.Vertices.Add(2.0, 2.0, 1.0); //10
        mesh.Vertices.Add(3.0, 2.0, 1.0); //11

        mesh.Faces.AddFace(0, 1, 5, 4);
        mesh.Faces.AddFace(1, 2, 6, 5);
        mesh.Faces.AddFace(2, 3, 7, 6);
        mesh.Faces.AddFace(4, 5, 9, 8);
        mesh.Faces.AddFace(5, 6, 10, 9);
        mesh.Faces.AddFace(6, 7, 11, 10);
        mesh.Normals.ComputeNormals();
        mesh.Compact();
        if (doc.Objects.AddMesh(mesh) != Guid.Empty)
        {
          doc.Views.Redraw();
          return Rhino.Commands.Result.Success;
        }
        return Rhino.Commands.Result.Failure;
    }
  public static Rhino.Commands.Result ExtractRenderMesh(Rhino.RhinoDoc doc)
  {
    Rhino.DocObjects.ObjRef objRef = null;
    Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetOneObject("Select surface or polysurface", false, Rhino.DocObjects.ObjectType.Brep, out objRef);
    if (rc != Rhino.Commands.Result.Success)
      return rc;

    Rhino.DocObjects.RhinoObject obj = objRef.Object();
    if (null == obj)
      return Rhino.Commands.Result.Failure;

    System.Collections.Generic.List<Rhino.DocObjects.RhinoObject> objList = new System.Collections.Generic.List<Rhino.DocObjects.RhinoObject>(1);
    objList.Add(obj);

    Rhino.DocObjects.ObjRef[] meshObjRefs = Rhino.DocObjects.RhinoObject.GetRenderMeshes(objList, true, false);
    if (null != meshObjRefs)
    {
      for (int i = 0; i < meshObjRefs.Length; i++)
      {
        Rhino.DocObjects.ObjRef meshObjRef = meshObjRefs[i];
        if (null != meshObjRef)
        {
          Rhino.Geometry.Mesh mesh = meshObjRef.Mesh();
          if (null != mesh)
            doc.Objects.AddMesh(mesh);
        }
      }
      doc.Views.Redraw();
    }

    return Rhino.Commands.Result.Success;
  }
예제 #12
0
  public static Rhino.Commands.Result ArcLengthPoint(Rhino.RhinoDoc doc)
  {
    Rhino.DocObjects.ObjRef objref;
    Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetOneObject("Select curve",
      true, Rhino.DocObjects.ObjectType.Curve,out objref);
    if(rc!= Rhino.Commands.Result.Success)
      return rc;
    Rhino.Geometry.Curve crv = objref.Curve();
    if( crv==null )
      return Rhino.Commands.Result.Failure;
 
    double crv_length = crv.GetLength();
    double length = 0;
    rc = Rhino.Input.RhinoGet.GetNumber("Length from start", true, ref length, 0, crv_length);
    if(rc!= Rhino.Commands.Result.Success)
      return rc;
 
    Rhino.Geometry.Point3d pt = crv.PointAtLength(length);
    if (pt.IsValid)
    {
      doc.Objects.AddPoint(pt);
      doc.Views.Redraw();
    }
    return Rhino.Commands.Result.Success;
  }
예제 #13
0
        /// <summary>
        /// Añade un vehículo del tipo especificado
        /// </summary>
        /// <param name="type">Tipo</param>
        /// <param name="where">Posición inicial</param>
        /// <returns>Devuelve el vehículo añadido</returns>
        public Vehicle AddVehicle(VehicleTypes type, Point where)
        {
            Vehicle newVehicle = null;

            if (type == VehicleTypes.Rhino)
            {
                newVehicle = new Rhino(this.Game, "Content/Vehicles");
            }
            else if (type == VehicleTypes.LandRaider)
            {
                newVehicle = new LandRaider(this.Game, "Content/Vehicles");
            }
            else if (type == VehicleTypes.LandSpeeder)
            {
                newVehicle = new LandSpeeder(this.Game, "Content/Vehicles");
            }
            else if (type == VehicleTypes.LemanRuss)
            {
                newVehicle = new LemanRuss(this.Game, "Content/Vehicles");
            }

            if (newVehicle != null)
            {
                newVehicle.UpdateOrder = this.UpdateOrder;

                this.Game.Components.Add(newVehicle);

                updateList = true;

                newVehicle.Position = new Vector3(where.X, 0f, where.Y);
            }

            return(newVehicle);
        }
예제 #14
0
  public static Rhino.Commands.Result InsertKnot(Rhino.RhinoDoc doc)
  {
    const ObjectType filter = Rhino.DocObjects.ObjectType.Curve;
    Rhino.DocObjects.ObjRef objref;
    Result rc = Rhino.Input.RhinoGet.GetOneObject("Select curve for knot insertion", false, filter, out objref);
    if (rc != Rhino.Commands.Result.Success)
      return rc;
    Rhino.Geometry.Curve curve = objref.Curve();
    if (null == curve)
      return Rhino.Commands.Result.Failure;
    Rhino.Geometry.NurbsCurve nurb = curve.ToNurbsCurve();
    if (null == nurb)
      return Rhino.Commands.Result.Failure;

    Rhino.Input.Custom.GetPoint gp = new Rhino.Input.Custom.GetPoint();
    gp.SetCommandPrompt("Point on curve to add knot");
    gp.Constrain(nurb, false);
    gp.Get();
    if (gp.CommandResult() == Rhino.Commands.Result.Success)
    {
      double t;
      Rhino.Geometry.Curve crv = gp.PointOnCurve(out t);
      if( crv!=null && nurb.Knots.InsertKnot(t) )
      {
        doc.Objects.Replace(objref, nurb);
        doc.Views.Redraw();
      }
    }
    return Rhino.Commands.Result.Success;  
  }
예제 #15
0
파일: MainTest.cs 프로젝트: yyht/rhino
        public void TestOutOfContext()
        {
            using Rhino r = SetUpClass();
            int frameLen = r.FrameLength;

            string       testAudioPath = Path.Combine(_relativeDir, "resources/audio_samples/test_out_of_context.wav");
            List <short> data          = GetPcmFromFile(testAudioPath, r.SampleRate);

            bool isFinalized = false;
            int  framecount  = (int)Math.Floor((float)(data.Count / frameLen));
            var  results     = new List <int>();

            for (int i = 0; i < framecount; i++)
            {
                int          start = i * r.FrameLength;
                int          count = r.FrameLength;
                List <short> frame = data.GetRange(start, count);
                isFinalized = r.Process(frame.ToArray());
                if (isFinalized)
                {
                    break;
                }
            }
            Assert.IsTrue(isFinalized, "Failed to finalize.");

            Inference inference = r.GetInference();

            Assert.IsFalse(inference.IsUnderstood, "Shouldn't be able to understand.");
        }
예제 #16
0
 internal static extern void CRhinoVisualAnalysisMode_SetCallbacks(Rhino.Display.VisualAnalysisMode.ANALYSISMODEENABLEUIPROC enableui_proc,
   Rhino.Display.VisualAnalysisMode.ANALYSISMODEOBJECTSUPPORTSPROC objectSupportProc,
   Rhino.Display.VisualAnalysisMode.ANALYSISMODESHOWISOCURVESPROC showIsoCurvesProc,
   Rhino.Display.VisualAnalysisMode.ANALYSISMODESETDISPLAYATTRIBUTESPROC displayAttributesProc,
   Rhino.Display.VisualAnalysisMode.ANALYSISMODEUPDATEVERTEXCOLORSPROC updateVertexColorsProc,
   Rhino.Display.VisualAnalysisMode.ANALYSISMODEDRAWRHINOOBJECTPROC drawRhinoObjectProc,
   Rhino.Display.VisualAnalysisMode.ANALYSISMODEDRAWGEOMETRYPROC drawGeometryProc);
예제 #17
0
 /// <summary>
 /// Generate a layout with a single detail view that zooms to a list of objects
 /// </summary>
 /// <param name="doc"></param>
 /// <returns></returns>
 public static Rhino.Commands.Result AddLayout(Rhino.RhinoDoc doc)
 {
     doc.PageUnitSystem = Rhino.UnitSystem.Millimeters;
     var page_views = doc.Views.GetPageViews();
     int page_number = (page_views==null) ? 1 : page_views.Length + 1;
     var pageview = doc.Views.AddPageView(string.Format("A0_{0}",page_number), 1189, 841);
     if( pageview!=null )
     {
       Rhino.Geometry.Point2d top_left = new Rhino.Geometry.Point2d(20,821);
       Rhino.Geometry.Point2d bottom_right = new Rhino.Geometry.Point2d(1169, 20);
       var detail = pageview.AddDetailView("ModelView", top_left, bottom_right, Rhino.Display.DefinedViewportProjection.Top);
       if (detail != null)
       {
     pageview.SetActiveDetail(detail.Id);
     detail.Viewport.ZoomExtents();
     detail.DetailGeometry.IsProjectionLocked = true;
     detail.DetailGeometry.SetScale(1, doc.ModelUnitSystem, 10, doc.PageUnitSystem);
     // Commit changes tells the document to replace the document's detail object
     // with the modified one that we just adjusted
     detail.CommitChanges();
       }
       pageview.SetPageAsActive();
       doc.Views.ActiveView = pageview;
       doc.Views.Redraw();
       return Rhino.Commands.Result.Success;
     }
     return Rhino.Commands.Result.Failure;
 }
예제 #18
0
  protected override void UpdateVertexColors(Rhino.DocObjects.RhinoObject obj, Mesh[] meshes)
  {
    // A "mapping tag" is used to determine if the colors need to be set
    Rhino.Render.MappingTag mt = GetMappingTag(obj.RuntimeSerialNumber);

    for (int mi = 0; mi < meshes.Length; mi++)
    {
      var mesh = meshes[mi];
      if( mesh.VertexColors.Tag.Id != this.Id )
      {
        // The mesh's mapping tag is different from ours. Either the mesh has
        // no false colors, has false colors set by another analysis mode, has
        // false colors set using different m_z_range[]/m_hue_range[] values, or
        // the mesh has been moved.  In any case, we need to set the false
        // colors to the ones we want.
        System.Drawing.Color[] colors = new System.Drawing.Color[mesh.Vertices.Count];
        for (int i = 0; i < mesh.Vertices.Count; i++)
        {
          double z = mesh.Vertices[i].Z;
          colors[i] = FalseColor(z);
        }
        mesh.VertexColors.SetColors(colors);
        // set the mesh's color tag 
        mesh.VertexColors.Tag = mt;
      }
    }
  }
예제 #19
0
    /// <summary>
    /// Rhino calls this function to run the command.
    /// </summary>
    protected override Rhino.Commands.Result RunCommand(Rhino.RhinoDoc doc, Rhino.Commands.RunMode mode)
    {
      const Rhino.DocObjects.ObjectType filter = Rhino.DocObjects.ObjectType.Curve;
      Rhino.DocObjects.ObjRef objref;
      Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetOneObject("Select curve to divide", false, filter, out objref);
      if (rc != Rhino.Commands.Result.Success || objref == null)
        return rc;

      Rhino.Geometry.Curve curve = objref.Curve();
      if (null == curve || curve.IsShort(Rhino.RhinoMath.ZeroTolerance))
        return Rhino.Commands.Result.Failure;

      int segmentCount = 2;
      rc = Rhino.Input.RhinoGet.GetInteger("Number of segments", false, ref segmentCount, 2, 100);
      if (rc != Rhino.Commands.Result.Success)
        return rc;

      Rhino.Geometry.Point3d[] points;
      curve.DivideByCount(segmentCount, true, out points);
      if (null == points)
        return Rhino.Commands.Result.Failure;

      // Create a history record
      Rhino.DocObjects.HistoryRecord history = new Rhino.DocObjects.HistoryRecord(this, _historyVersion);
      WriteHistory(history, objref, segmentCount, points.Length);

      for (int i = 0; i < points.Length; i++)
        doc.Objects.AddPoint(points[i], null, history, false);

      doc.Views.Redraw();

      return Rhino.Commands.Result.Success;
    }
예제 #20
0
  protected override Rhino.Commands.Result RunCommand(RhinoDoc doc, Rhino.Commands.RunMode mode)
  {
    // make sure our custom visual analysis mode is registered
    var zmode = Rhino.Display.VisualAnalysisMode.Register(typeof(ZAnalysisMode));

    const ObjectType filter = Rhino.DocObjects.ObjectType.Surface | Rhino.DocObjects.ObjectType.PolysrfFilter | Rhino.DocObjects.ObjectType.Mesh;
    Rhino.DocObjects.ObjRef[] objs;
    var rc = Rhino.Input.RhinoGet.GetMultipleObjects("Select objects for Z analysis", false, filter, out objs);
    if (rc != Rhino.Commands.Result.Success)
      return rc;

    int count = 0;
    for (int i = 0; i < objs.Length; i++)
    {
      var obj = objs[i].Object();

      // see if this object is alreay in Z analysis mode
      if (obj.InVisualAnalysisMode(zmode))
        continue;

      if (obj.EnableVisualAnalysisMode(zmode, true))
        count++;
    }
    doc.Views.Redraw();
    RhinoApp.WriteLine("{0} objects were put into Z-Analysis mode.", count);
    return Rhino.Commands.Result.Success;
  }
 protected override Rhino.Commands.Result  RunCommand(RhinoDoc doc, Rhino.Commands.RunMode mode)
 {
     //List<Rhino.DocObjects.RhinoObject> ObjectList = new List<Rhino.DocObjects.RhinoObject>();
     Rhino.DocObjects.ObjectEnumeratorSettings settings = new Rhino.DocObjects.ObjectEnumeratorSettings();
     settings.DeletedObjects = false;
     settings.HiddenObjects = false;
     settings.LockedObjects = true;
     settings.NormalObjects = true;
     settings.VisibleFilter = true;
     settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.Brep & Rhino.DocObjects.ObjectType.Surface & Rhino.DocObjects.ObjectType.Extrusion;
     List<Rhino.DocObjects.RhinoObject> RC_List = new List<Rhino.DocObjects.RhinoObject>();
     foreach (Rhino.DocObjects.RhinoObject RHobj in Rhino.RhinoDoc.ActiveDoc.Objects.GetObjectList(settings))
     {
         if (RHobj.ObjectType == Rhino.DocObjects.ObjectType.Brep || RHobj.ObjectType == Rhino.DocObjects.ObjectType.Surface || RHobj.ObjectType == Rhino.DocObjects.ObjectType.Extrusion)
         {
             RC_List.Add(RHobj);
         }
     }
     if (RC_List.Count != 0)
     {
         Ret_NURBS_Scene = new RhCommon_Scene(RC_List, Air_Temp, Rel_Humidity, Atm_pressure, Atten_Choice, Edge_Freq, false);
         if (!Ret_NURBS_Scene.Valid) return Rhino.Commands.Result.Failure;
         Ret_Mesh_Scene = new Polygon_Scene(RC_List, Air_Temp, Rel_Humidity, Atm_pressure, Atten_Choice, Edge_Freq, false);
         if (!Ret_Mesh_Scene.Valid) return Rhino.Commands.Result.Failure;
     }
     C_Result = Rhino.Commands.Result.Success;
     return Rhino.Commands.Result.Success;
 }
        public ActionResult Create(Rhino.Security.Mgmt.Dtos.PermissionDto item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            using (_conversation.SetAsCurrent())
            {
                Permission permissionToReturn = null;
                var itemMapped = _mapper.Map<Rhino.Security.Mgmt.Dtos.PermissionDto, Rhino.Security.Model.Permission>(item);
                Rhino.Security.Mgmt.Infrastructure.Mvc.ValidationHelpers.AddErrorsToModelState(ModelState, _validator.Validate(itemMapped), "item");
                if (ModelState.IsValid)
                {
                    permissionToReturn = _repository.Create(itemMapped);
                    _conversation.Flush();
                }

                return Json(new
                {
                    item = GetPermissionViewModel(permissionToReturn),
                    success = ModelState.IsValid,
                    errors = Rhino.Security.Mgmt.Infrastructure.Mvc.ValidationHelpers.BuildErrorDictionary(ModelState),
                });
            }
        }
예제 #23
0
    protected override Rhino.Commands.Result RunCommand(Rhino.RhinoDoc doc, Rhino.Commands.RunMode mode)
    {
      string filename = string.Empty;
      if (mode == Rhino.Commands.RunMode.Interactive)
        filename = Rhino.Input.RhinoGet.GetFileName(Rhino.Input.Custom.GetFileNameMode.OpenRhinoOnly, null, "Import", Rhino.RhinoApp.MainWindow());
      else
        Rhino.Input.RhinoGet.GetString("Name of Rhino file to import", false, ref filename);

      filename = filename.Trim();
      if (string.IsNullOrEmpty(filename))
        return Rhino.Commands.Result.Cancel;

      if (!System.IO.File.Exists(filename))
      {
        Rhino.RhinoApp.WriteLine("File not found.");
        return Rhino.Commands.Result.Failure;
      }

      // Make sure to surround filename string with double-quote characters
      // in case the path contains spaces.
      string script = string.Format("_-Import \"{0}\" _Enter", filename);
      Rhino.RhinoApp.RunScript(script, false);
      
      return Rhino.Commands.Result.Success;
    }
예제 #24
0
  public static Rhino.Commands.Result DivideByLengthPoints(Rhino.RhinoDoc doc)
  {
    Rhino.DocObjects.ObjectType filter = Rhino.DocObjects.ObjectType.Curve; 
    Rhino.DocObjects.ObjRef objref = null;
    Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetOneObject("Select curve to divide", false, filter, out objref);
    if (rc != Rhino.Commands.Result.Success || objref == null)
      return rc;

    Rhino.Geometry.Curve crv = objref.Curve();
    if (crv == null || crv.IsShort(Rhino.RhinoMath.ZeroTolerance))
      return Rhino.Commands.Result.Failure;

    double crv_length = crv.GetLength();
    string s = string.Format("Curve length is {0:f3}. Segment length", crv_length);

    double seg_length = crv_length / 2.0;
    rc = Rhino.Input.RhinoGet.GetNumber(s, false, ref seg_length, 0, crv_length);
    if (rc != Rhino.Commands.Result.Success)
      return rc;

    Rhino.Geometry.Point3d[] points = null;
    crv.DivideByLength(seg_length, true, out points);
    if (points == null)
      return Rhino.Commands.Result.Failure;

    foreach (Rhino.Geometry.Point3d point in points)
      doc.Objects.AddPoint(point);

    doc.Views.Redraw();
    return Rhino.Commands.Result.Success;
  }
예제 #25
0
  public static Rhino.Commands.Result DupBorder(Rhino.RhinoDoc doc)
  {
    const ObjectType filter = Rhino.DocObjects.ObjectType.Surface | Rhino.DocObjects.ObjectType.PolysrfFilter;
    Rhino.DocObjects.ObjRef objref;
    Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetOneObject("Select surface or polysurface", false, filter, out objref);
    if (rc != Rhino.Commands.Result.Success || objref == null)
      return rc;

    Rhino.DocObjects.RhinoObject rhobj = objref.Object();
    Rhino.Geometry.Brep brep = objref.Brep();
    if (rhobj == null || brep == null)
      return Rhino.Commands.Result.Failure;

    rhobj.Select(false);
    Rhino.Geometry.Curve[] curves = brep.DuplicateEdgeCurves(true);
    double tol = doc.ModelAbsoluteTolerance * 2.1;
    curves = Rhino.Geometry.Curve.JoinCurves(curves, tol);
    for (int i = 0; i < curves.Length; i++)
    {
      Guid id = doc.Objects.AddCurve(curves[i]);
      doc.Objects.Select(id);
    }
    doc.Views.Redraw();
    return Rhino.Commands.Result.Success;
  }
예제 #26
0
  public static Rhino.Commands.Result CircleCenter(Rhino.RhinoDoc doc)
  {
    Rhino.Input.Custom.GetObject go = new Rhino.Input.Custom.GetObject();
    go.SetCommandPrompt("Select objects");
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve;
    go.GeometryAttributeFilter = Rhino.Input.Custom.GeometryAttributeFilter.ClosedCurve;
    go.GetMultiple(1, 0);
    if( go.CommandResult() != Rhino.Commands.Result.Success )
      return go.CommandResult();

    Rhino.DocObjects.ObjRef[] objrefs = go.Objects();
    if( objrefs==null )
      return Rhino.Commands.Result.Nothing;

    double tolerance = doc.ModelAbsoluteTolerance;
    for( int i=0; i<objrefs.Length; i++ )
    {
      // get the curve geometry
      Rhino.Geometry.Curve curve = objrefs[i].Curve();
      if( curve==null )
        continue;
      Rhino.Geometry.Circle circle;
      if( curve.TryGetCircle(out circle, tolerance) )
      {
        Rhino.RhinoApp.WriteLine("Circle{0}: center = {1}", i+1, circle.Center);
      }
    }
    return Rhino.Commands.Result.Success;
  }
  public static Rhino.Commands.Result AddClippingPlane(Rhino.RhinoDoc doc)
  {
    // Define the corners of the clipping plane
    Rhino.Geometry.Point3d[] corners;
    Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetRectangle(out corners);
    if (rc != Rhino.Commands.Result.Success)
      return rc;

    // Get the active view
    Rhino.Display.RhinoView view = doc.Views.ActiveView;
    if (view == null)
      return Rhino.Commands.Result.Failure;

    Rhino.Geometry.Point3d p0 = corners[0];
    Rhino.Geometry.Point3d p1 = corners[1];
    Rhino.Geometry.Point3d p3 = corners[3];

    // Create a plane from the corner points
    Rhino.Geometry.Plane plane = new Rhino.Geometry.Plane(p0, p1, p3);

    // Add a clipping plane object to the document
    Guid id = doc.Objects.AddClippingPlane(plane, p0.DistanceTo(p1), p0.DistanceTo(p3), view.ActiveViewportID);
    if (id != Guid.Empty)
    {
      doc.Views.Redraw();
      return Rhino.Commands.Result.Success;
    }
    return Rhino.Commands.Result.Failure;
  }
예제 #28
0
    public static Rhino.Commands.Result Bend(Rhino.RhinoDoc doc)
    {
        ObjectType filter = SpaceMorphObjectFilter();
        Rhino.DocObjects.ObjRef objref;
        Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetOneObject("Select object to bend", false, filter, out objref);
        if (rc != Rhino.Commands.Result.Success || objref == null)
          return rc;

        Rhino.Geometry.Line axis;
        rc = Rhino.Input.RhinoGet.GetLine(out axis);
        if (rc != Rhino.Commands.Result.Success || axis == null)
          return rc;

        Rhino.Geometry.Point3d point;
        rc = Rhino.Input.RhinoGet.GetPoint("Point to bend through", false, out point);
        if (rc != Rhino.Commands.Result.Success || !point.IsValid)
          return rc;

        Rhino.Geometry.Morphs.BendSpaceMorph morph = new Rhino.Geometry.Morphs.BendSpaceMorph(axis.From, axis.To, point, true, false);

        Rhino.Geometry.GeometryBase geom = objref.Geometry().Duplicate();
        if (morph.Morph(geom))
        {
          doc.Objects.Add(geom);
          doc.Views.Redraw();
        }

        return Rhino.Commands.Result.Success;
    }
예제 #29
0
    protected override Rhino.Commands.Result RunCommand(RhinoDoc doc, Rhino.Commands.RunMode mode)
    {
      var conduit = new PointsConduit(m_conduit_points);
      conduit.Enabled = true;

      var gp = new Rhino.Input.Custom.GetPoint();
      while (true)
      {
        gp.SetCommandPrompt("click location to create point. (<ESC> exit)");
        gp.AcceptNothing(true);
        gp.Get();
        if (gp.CommandResult() != Rhino.Commands.Result.Success)
          break;
        m_conduit_points.Add(new ConduitPoint(gp.Point()));
        doc.Views.Redraw();
      }

      var gcp = new GetConduitPoint(m_conduit_points);
      while (true)
      {
        gcp.SetCommandPrompt("select conduit point. (<ESC> to exit)");
        gcp.AcceptNothing(true);
        gcp.Get(true);
        doc.Views.Redraw();
        if (gcp.CommandResult() != Rhino.Commands.Result.Success)
          break;
      }

      return Rhino.Commands.Result.Success;
    }
예제 #30
0
    public static Rhino.Commands.Result TweenCurve(Rhino.RhinoDoc doc)
    {
        Rhino.Input.Custom.GetObject go = new Rhino.Input.Custom.GetObject();
        go.SetCommandPrompt("Select two curves");
        go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve;
        go.GetMultiple(2, 2);
        if (go.CommandResult() != Rhino.Commands.Result.Success)
          return go.CommandResult();

        Rhino.Geometry.Curve curve0 = go.Object(0).Curve();
        Rhino.Geometry.Curve curve1 = go.Object(1).Curve();
        if (null != curve0 && null != curve1)
        {
          Rhino.Geometry.Curve[] curves = Rhino.Geometry.Curve.CreateTweenCurves(curve0, curve1, 1);
          if (null != curves)
          {
        for (int i = 0; i < curves.Length; i++)
          doc.Objects.AddCurve(curves[i]);

        doc.Views.Redraw();
        return Rhino.Commands.Result.Success;
          }
        }

        return Rhino.Commands.Result.Failure;
    }
    public static Rhino.Commands.Result ActiveViewport(Rhino.RhinoDoc doc)
    {
        Rhino.Display.RhinoView view = doc.Views.ActiveView;
        if (view == null)
          return Rhino.Commands.Result.Failure;

        Rhino.Display.RhinoPageView pageview = view as Rhino.Display.RhinoPageView;
        if (pageview != null)
        {
          string layout_name = pageview.PageName;
          if (pageview.PageIsActive)
          {
        Rhino.RhinoApp.WriteLine("The layout {0} is active", layout_name);
          }
          else
          {
        string detail_name = pageview.ActiveViewport.Name;
        Rhino.RhinoApp.WriteLine("The detail {0} on layout {1} is active", detail_name, layout_name);
          }
        }
        else
        {
          string viewport_name = view.MainViewport.Name;
          Rhino.RhinoApp.WriteLine("The viewport {0} is active", viewport_name);
        }
        return Rhino.Commands.Result.Success;
    }
예제 #32
0
 /// <summary>
 /// Returns the underlying const CRhinoObject* for a RhinoCommon class. You should only
 /// be interested in using this function if you are writing C++ code.
 /// </summary>
 /// <param name="rhinoObject">A Rhino object.</param>
 /// <returns>A pointer to the Rhino const object.</returns>
 public static IntPtr RhinoObjectConstPointer(Rhino.DocObjects.RhinoObject rhinoObject)
 {
   IntPtr rc = IntPtr.Zero;
   if (rhinoObject != null)
     rc = rhinoObject.ConstPointer();
   return rc;
 }
예제 #33
0
    private void OnEnable()
    {
        rnd = Random.Range(0, 3);
        Debug.Log("Rolled: " + rnd);
        switch (rnd)
        {
        case 0:
        {
            Rhino.SetActive(true);
            Rhino.transform.position = Spawner1.transform.position;

            break;
        }

        case 1:
        {
            Bus.SetActive(true);
            Bus.transform.position = Spawner1.transform.position;

            break;
        }

        case 2:
        {
            Ute.SetActive(true);
            Ute.transform.position = Spawner1.transform.position;

            break;
        }
        }

        rnd = Random.Range(0, 3);
        switch (rnd)
        {
        case 0:
        {
            Rhino2.SetActive(true);
            Rhino2.transform.position = Spawner2.transform.position;

            break;
        }

        case 1:
        {
            Bus2.SetActive(true);
            Bus2.transform.position = Spawner2.transform.position;

            break;
        }

        case 2:
        {
            U2.SetActive(true);
            U2.transform.position = Spawner2.transform.position;

            break;
        }
        }
    }
예제 #34
0
        public void CheckRhinoMove()
        {
            Rhino rhino = new Rhino();

            string rhinoMove = rhino.Move();

            Assert.Equal("Rumble but slower", rhinoMove);
        }
예제 #35
0
        /// <summary>
        /// Ajouter un rhinocéros bébé
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void AjouterBebeRhino(int x, int y)
        {
            Rhino rhino = new Rhino(x, y, GenererGenreAnimal(), Vieillesse.Bebe, GenererEtatAnimal(), tabAjout, Logique.TypeAnimal.Rhino, listeAnimal, hero);

            rhino.Enceinte = Enceinte.Non;
            listeAnimal.Add(rhino);
            AjoutVisiteur();
        }
예제 #36
0
        public void CheckRhinoMoos()
        {
            Rhino rhino = new Rhino();

            string rhinoSound = rhino.MakeSound();

            Assert.Equal("Moooo", rhinoSound);
        }
예제 #37
0
        public void RhinoHornCleaning()
        {
            Rhino  testRhino = new Rhino();
            string result    = testRhino.RhinoHornClean();
            string expected  = "Rhino's clean their horns once a month.";

            Assert.Equal(expected, result);
        }
예제 #38
0
        public bool RhinoBlast()
        {
            Rhino  testRhino = new Rhino();
            string result    = testRhino.RhinoNoise();
            string expected  = "Rhino's blast off with their horns!";

            Assert.Equal(expected, result);

            return(true);
        }
예제 #39
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestOutOfContext()
        {
            using Rhino rhino = InitDefaultRhino();

            RunTestCase(
                rhino,
                "test_out_of_context.wav",
                false
                );
        }
예제 #40
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Animal[] animals = new Animal[5];
            ISpeak[] Speaker = new ISpeak[4];

            Manticore ElPapi = new Manticore {
                Name = "ElPapi", Diet = "Blood and Bones", Lift = (1000 * 32.17), Intro = "I am ElPapi"
            };
            Mermaid KanyeBass = new Mermaid {
                Name = "KanyeBass", Diet = "FishSticks", IsIntelligent = false, Intro = "I love FishSticks"
            };
            Eagle Freedom = new Eagle {
                Name = "Freedom", HasFins = false, NumWings = 50, Lift = 1817, Diet = "Worms"
            };
            Rhino Rocksteady = new Rhino {
                Name = "Rocksteady", NumOfLegs = 4, Diet = "Meat and more meat", Intro = "I'm gonna crush those pesky ninja turtles"
            };
            Dragon Oenomaus = new Dragon {
                Name = "Oenomaus", IsIntelligent = true, Intro = "Im a DAWG BOWWWWWWW", Diet = "All meat baby", HasTeeth = true
            };

            Speaker[0] = ElPapi;
            Speaker[1] = KanyeBass;
            Speaker[2] = Rocksteady;
            Speaker[3] = Oenomaus;

            animals[0] = ElPapi;
            animals[1] = KanyeBass;
            animals[2] = Freedom;
            animals[3] = Rocksteady;
            animals[4] = Oenomaus;

            for (int i = 0; i < Speaker.Length; i++)
            {
                var speakers = Speaker[i];

                if (speakers is HasWings)
                {
                    var speakingWings = (HasWings)speakers;
                    speakingWings.ImFlying();
                }
                else if (speakers is NoWings)
                {
                    var grounded = (NoWings)speakers;
                    grounded.GroundBB();
                }
            }
            for (int i = 0; i < animals.Length; i++)
            {
                Console.WriteLine($"My name is {animals[i].Name} and I like to eat {animals[i].Diet}");
            }
        }
예제 #41
0
파일: FileDemo.cs 프로젝트: yyht/rhino
        /// <summary>
        /// Reads through input file and prints the inference result returned by Rhino.
        /// </summary>
        /// <param name="inputAudioPath">Required argument. Absolute path to input audio file.</param>
        /// <param name="contextPath">Required argument. Absolute path to the Rhino context file.</param>
        /// <param name="modelPath">Absolute path to the file containing model parameters. If not set it will be set to the default location.</param>
        /// <param name="sensitivity">
        /// Inference sensitivity. It should be a number within [0, 1]. A higher sensitivity value results in
        /// fewer misses at the cost of (potentially) increasing the erroneous inference rate. If not set, the default value of 0.5 will be used.
        /// </param>
        public static void RunDemo(string inputAudioPath, string contextPath, string modelPath, float sensitivity)
        {
            // init rhino speech-to-intent engine
            using Rhino rhino = Rhino.Create(contextPath, modelPath, sensitivity);

            // open and validate wav file
            using BinaryReader reader = new BinaryReader(File.Open(inputAudioPath, FileMode.Open));
            ValidateWavFile(reader, rhino.SampleRate, 16, out short numChannels);

            // read audio and send frames to rhino
            short[] rhinoFrame = new short[rhino.FrameLength];
            int     frameIndex = 0;

            while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                rhinoFrame[frameIndex++] = reader.ReadInt16();

                if (frameIndex == rhinoFrame.Length)
                {
                    bool isFinalized = rhino.Process(rhinoFrame);
                    if (isFinalized)
                    {
                        Inference inference = rhino.GetInference();
                        if (inference.IsUnderstood)
                        {
                            Console.WriteLine("{");
                            Console.WriteLine($"  intent : '{inference.Intent}'");
                            Console.WriteLine("  slots : {");
                            foreach (KeyValuePair <string, string> slot in inference.Slots)
                            {
                                Console.WriteLine($"    {slot.Key} : '{slot.Value}'");
                            }
                            Console.WriteLine("  }");
                            Console.WriteLine("}");
                        }
                        else
                        {
                            Console.WriteLine("Didn't understand the command.");
                        }
                        return;
                    }

                    frameIndex = 0;
                }

                // skip right channel
                if (numChannels == 2)
                {
                    reader.ReadInt16();
                }
            }

            Console.WriteLine("Reached end of audio file before Rhino returned an inference.");
        }
예제 #42
0
        /// <summary>
        /// Ajouter un rhinocéros adulte
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void AjouterAdulteRhino(int x, int y)
        {
            Rhino rhino = new Rhino(x, y, GenererGenreAnimal(), Vieillesse.Adulte, GenererEtatAnimal(), tabAjout, Logique.TypeAnimal.Rhino, listeAnimal, hero);

            if (rhino.Genre == Genre.Femelle)
            {
                rhino.Enceinte = rhino.GenererEnceinteAnimal();
            }
            listeAnimal.Add(rhino);
            AjoutVisiteur();
        }
예제 #43
0
        public void TestThatRhinoiInheritsBehaviors()
        {
            Rhino hornBoy = new Rhino()
            {
                Name = "HornBoy"
            };

            string input    = $"{hornBoy.Name} {hornBoy.IsAPet()}";
            string expected = $"{hornBoy.Name} Am I your pet?";

            Assert.Equal(expected, input);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            IAnimal animal1 = new Dog {
                Name = "Ben", TimesBarked = 30
            };
            IAnimal animal2 = new Rhino {
                Name = "James"
            };

            MessageBox.Show($"GetType : {animal1.GetType()}");

            PeopleWillTellYouToNotDoThis(animal1);
            PeopleWillTellYouToNotDoThis(animal2);
        }
예제 #45
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestOutOfContextDe()
        {
            string language = "de";

            using Rhino rhino = Rhino.Create(
                      ACCESS_KEY,
                      GetContextPath(language, "beleuchtung"),
                      GetModelPath(language));

            RunTestCase(
                rhino,
                "test_out_of_context_de.wav",
                false
                );
        }
예제 #46
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestOutOfContextEs()
        {
            string language = "es";

            using Rhino rhino = Rhino.Create(
                      ACCESS_KEY,
                      GetContextPath(language, "iluminación_inteligente"),
                      GetModelPath(language));

            RunTestCase(
                rhino,
                "test_out_of_context_es.wav",
                false
                );
        }
예제 #47
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestOutOfContextFr()
        {
            string language = "fr";

            using Rhino rhino = Rhino.Create(
                      ACCESS_KEY,
                      GetContextPath(language, "éclairage_intelligent"),
                      GetModelPath(language));

            RunTestCase(
                rhino,
                "test_out_of_context_fr.wav",
                false
                );
        }
예제 #48
0
        public Unit GetDefender()
        {
            //var unit = GreyHunters.Create(true, false, true, 4, 1, 0);
            //var unit = LandSpeeders.Create(LandSpeederTypes.Default, LandSpeederWeaponTypes.AssaultCannon, 3);
            //var unit = Intercessors.Create(true, 4);
            //var unit = WarBikers.Create(true, 5);
            //var unit = Boyz.Create(false, 27, 0, 3);
            //var unit = ArmigerWarglaive.Create(ArmigerWarglaiveTypes.Default);
            //var unit = KnightPreceptor.Create(KnightPreceptorTypes.Default);
            //var unit = Gunwagon.Create(GunwagonTypes.ZzapGun, 4);
            //var unit = ArmigerHelverin.Create(ArmigerHelverinTypes.Default);
            var unit = Rhino.Create();

            //var unit = Razorback.Create(RazorBackTypes.TwinHeavyBolter, true, true);

            return(unit);
        }
예제 #49
0
        public void TestWithinContext()
        {
            using Rhino r = SetUpClass();
            int frameLen = r.FrameLength;

            string       testAudioPath = Path.Combine(_relativeDir, "resources/audio_samples/test_within_context.wav");
            List <short> data          = GetPcmFromFile(testAudioPath, r.SampleRate);

            bool isFinalized = false;
            int  framecount  = (int)Math.Floor((float)(data.Count / frameLen));
            var  results     = new List <int>();

            for (int i = 0; i < framecount; i++)
            {
                int          start = i * r.FrameLength;
                int          count = r.FrameLength;
                List <short> frame = data.GetRange(start, count);
                isFinalized = r.Process(frame.ToArray());
                if (isFinalized)
                {
                    break;
                }
            }
            Assert.IsTrue(isFinalized, "Failed to finalize.");

            Inference inference = r.GetInference();

            Assert.IsTrue(inference.IsUnderstood, "Couldn't understand.");
            Assert.AreEqual("orderDrink", inference.Intent, "Incorrect intent.");

            Dictionary <string, string> expectedSlotValues = new Dictionary <string, string>()
            {
                { "size", "medium" },
                { "numberOfShots", "double shot" },
                { "coffeeDrink", "americano" },
                { "milkAmount", "lots of milk" },
                { "sugarAmount", "some sugar" },
            };

            Assert.IsTrue(inference.Slots.All((keyValuePair) =>
                                              expectedSlotValues.ContainsKey(keyValuePair.Key) &&
                                              expectedSlotValues[keyValuePair.Key] == keyValuePair.Value));
        }
예제 #50
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestWithinContext()
        {
            using Rhino rhino = InitDefaultRhino();

            Dictionary <string, string> expectedSlots = new Dictionary <string, string>()
            {
                { "size", "medium" },
                { "numberOfShots", "double shot" },
                { "beverage", "americano" },
            };

            RunTestCase(
                rhino,
                "test_within_context.wav",
                true,
                "orderBeverage",
                expectedSlots
                );
        }
예제 #51
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        private void RunTestCase(
            Rhino rhino,
            string audioFileName,
            bool isWithinContext,
            string expectedIntent = null,
            Dictionary <string, string> expectedSlots = null)
        {
            int          frameLen      = rhino.FrameLength;
            string       testAudioPath = Path.Combine(_relativeDir, "resources/audio_samples", audioFileName);
            List <short> data          = GetPcmFromFile(testAudioPath, rhino.SampleRate);

            bool isFinalized = false;
            int  framecount  = (int)Math.Floor((float)(data.Count / frameLen));
            var  results     = new List <int>();

            for (int i = 0; i < framecount; i++)
            {
                int          start = i * rhino.FrameLength;
                int          count = rhino.FrameLength;
                List <short> frame = data.GetRange(start, count);
                isFinalized = rhino.Process(frame.ToArray());
                if (isFinalized)
                {
                    break;
                }
            }
            Assert.IsTrue(isFinalized, "Failed to finalize.");

            Inference inference = rhino.GetInference();

            if (isWithinContext)
            {
                Assert.IsTrue(inference.IsUnderstood, "Couldn't understand.");
                Assert.AreEqual(expectedIntent, inference.Intent, "Incorrect intent.");
                Assert.IsTrue(inference.Slots.All((keyValuePair) =>
                                                  expectedSlots.ContainsKey(keyValuePair.Key) &&
                                                  expectedSlots[keyValuePair.Key] == keyValuePair.Value));
            }
            else
            {
                Assert.IsFalse(inference.IsUnderstood, "Shouldn't be able to understand.");
            }
        }
예제 #52
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestWithinContextDe()
        {
            string language = "de";

            using Rhino rhino = Rhino.Create(
                      ACCESS_KEY,
                      GetContextPath(language, "beleuchtung"),
                      GetModelPath(language));

            Dictionary <string, string> expectedSlots = new Dictionary <string, string>()
            {
                { "state", "aus" }
            };

            RunTestCase(
                rhino,
                "test_within_context_de.wav",
                true,
                "changeState",
                expectedSlots
                );
        }
예제 #53
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestWithinContextFr()
        {
            string language = "fr";

            using Rhino rhino = Rhino.Create(
                      ACCESS_KEY,
                      GetContextPath(language, "éclairage_intelligent"),
                      GetModelPath(language));

            Dictionary <string, string> expectedSlots = new Dictionary <string, string>()
            {
                { "color", "violet" }
            };

            RunTestCase(
                rhino,
                "test_within_context_fr.wav",
                true,
                "changeColor",
                expectedSlots
                );
        }
예제 #54
0
파일: MainTest.cs 프로젝트: Picovoice/rhino
        public void TestWithinContextEs()
        {
            string language = "es";

            using Rhino rhino = Rhino.Create(
                      ACCESS_KEY,
                      GetContextPath(language, "iluminación_inteligente"),
                      GetModelPath(language));

            Dictionary <string, string> expectedSlots = new Dictionary <string, string>()
            {
                { "location", "habitación" },
                { "color", "rosado" }
            };

            RunTestCase(
                rhino,
                "test_within_context_es.wav",
                true,
                "changeColor",
                expectedSlots
                );
        }
예제 #55
0
        public void CheckRhinoTypeOfCanBeRidden()
        {
            Rhino rhino = new Rhino();

            Assert.IsType <bool>(rhino.CanBeRidden);
        }
예제 #56
0
파일: MainTest.cs 프로젝트: yyht/rhino
 public void TestFrameLength()
 {
     using Rhino r = SetUpClass();
     Assert.IsTrue(r?.FrameLength > 0, "Specified frame length was not a valid number.");
 }
예제 #57
0
파일: MicDemo.cs 프로젝트: yyht/rhino
        /// <summary>
        /// Creates an input audio stream, instantiates an instance of Rhino object, and infers the intent from spoken commands.
        /// </summary>
        /// <param name="contextPath">
        /// Absolute path to file containing context model (file with `.rhn` extension). A context represents the set of
        /// expressions(spoken commands), intents, and intent arguments(slots) within a domain of interest.
        /// </param>
        /// <param name="modelPath">Absolute path to the file containing model parameters. If not set it will be set to the default location.</param>
        /// <param name="sensitivity">
        /// Inference sensitivity. It should be a number within [0, 1]. A higher sensitivity value results in
        /// fewer misses at the cost of (potentially) increasing the erroneous inference rate. If not set, the default value of 0.5 will be used.
        /// </param>
        /// <param name="audioDeviceIndex">Optional argument. If provided, audio is recorded from this input device. Otherwise, the default audio input device is used.</param>
        /// <param name="outputPath">Optional argument. If provided, recorded audio will be stored in this location at the end of the run.</param>
        public static void RunDemo(string contextPath, string modelPath, float sensitivity, int?audioDeviceIndex = null, string outputPath = null)
        {
            Rhino        rhino               = null;
            BinaryWriter outputFileWriter    = null;
            int          totalSamplesWritten = 0;

            try
            {
                // init rhino speech-to-intent engine
                rhino = Rhino.Create(contextPath, modelPath, sensitivity);

                // open stream to output file
                if (!string.IsNullOrWhiteSpace(outputPath))
                {
                    outputFileWriter = new BinaryWriter(new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write));
                    WriteWavHeader(outputFileWriter, 1, 16, 16000, 0);
                }

                // choose audio device
                string deviceName = null;
                if (audioDeviceIndex != null)
                {
                    List <string> captureDeviceList = ALC.GetStringList(GetEnumerationStringList.CaptureDeviceSpecifier).ToList();
                    if (captureDeviceList != null && audioDeviceIndex.Value < captureDeviceList.Count)
                    {
                        deviceName = captureDeviceList[audioDeviceIndex.Value];
                    }
                    else
                    {
                        throw new ArgumentException("No input device found with the specified index. Use --show_audio_devices to show" +
                                                    "available inputs", "--audio_device_index");
                    }
                }

                Console.WriteLine(rhino.ContextInfo);
                Console.WriteLine("Listening...\n");

                // create and start recording
                short[]         recordingBuffer = new short[rhino.FrameLength];
                ALCaptureDevice captureDevice   = ALC.CaptureOpenDevice(deviceName, 16000, ALFormat.Mono16, rhino.FrameLength * 2);
                {
                    ALC.CaptureStart(captureDevice);
                    while (!Console.KeyAvailable)
                    {
                        int samplesAvailable = ALC.GetAvailableSamples(captureDevice);
                        if (samplesAvailable > rhino.FrameLength)
                        {
                            ALC.CaptureSamples(captureDevice, ref recordingBuffer[0], rhino.FrameLength);
                            bool isFinalized = rhino.Process(recordingBuffer);
                            if (isFinalized)
                            {
                                Inference inference = rhino.GetInference();
                                if (inference.IsUnderstood)
                                {
                                    Console.WriteLine("{");
                                    Console.WriteLine($"  intent : '{inference.Intent}'");
                                    Console.WriteLine("  slots : {");
                                    foreach (KeyValuePair <string, string> slot in inference.Slots)
                                    {
                                        Console.WriteLine($"    {slot.Key} : '{slot.Value}'");
                                    }
                                    Console.WriteLine("  }");
                                    Console.WriteLine("}");
                                }
                                else
                                {
                                    Console.WriteLine("Didn't understand the command.");
                                }
                            }

                            if (outputFileWriter != null)
                            {
                                foreach (short sample in recordingBuffer)
                                {
                                    outputFileWriter.Write(sample);
                                }
                                totalSamplesWritten += recordingBuffer.Length;
                            }
                        }
                        Thread.Yield();
                    }

                    // stop and clean up resources
                    Console.WriteLine("Stopping...");
                    ALC.CaptureStop(captureDevice);
                    ALC.CaptureCloseDevice(captureDevice);
                }
            }
            finally
            {
                if (outputFileWriter != null)
                {
                    // write size to header and clean up
                    WriteWavHeader(outputFileWriter, 1, 16, 16000, totalSamplesWritten);
                    outputFileWriter.Flush();
                    outputFileWriter.Dispose();
                }
                rhino?.Dispose();
            }
        }
예제 #58
0
        static void Main(string[] args)
        {
            Console.WriteLine("Animals can Eat, Move, Sleep, and Make a Sound.\n");

            Console.WriteLine("\nCanines are Animals that can Sniff, Swim, and Mark Territory.\n");
            Console.WriteLine("\nDog inherits from Animal and Canine. See the dog do things:");
            Dog dog = new Dog();

            Console.WriteLine(dog.Eat());
            Console.WriteLine(dog.Sleep());
            Console.WriteLine(dog.Move());
            Console.WriteLine(dog.MakeSound());
            Console.WriteLine(dog.Sniff());
            Console.WriteLine(dog.Swim());
            Console.WriteLine(dog.MarkTerritory());
            Console.WriteLine(dog.RespondToDanger());
            Console.WriteLine($"A {dog.Name} has {dog.NumOfLegs} legs.");
            dog.HasFur = true;  // This will turn dog.HasFur to false due to HasFur implementation
            Console.WriteLine($"A {dog.Name} has fur? {dog.HasFur}");

            Console.WriteLine("\nWolf inherits from Animal and Canine. See the wolf do things:");
            Wolf wolf = new Wolf();

            Console.WriteLine(wolf.Eat());
            Console.WriteLine(wolf.Sleep());
            Console.WriteLine(wolf.Move());
            Console.WriteLine(wolf.MakeSound());
            Console.WriteLine(wolf.Sniff());
            Console.WriteLine(wolf.Swim());
            Console.WriteLine(wolf.MarkTerritory());
            Console.WriteLine(wolf.RespondToDanger());
            Console.WriteLine($"A {wolf.Name} has {wolf.NumOfLegs} legs.");
            Console.WriteLine($"A {wolf.Name} has fur? {wolf.HasFur}");

            Console.WriteLine("\nFish are Animals that can Breathe Underwater and Find A School.\n");
            Console.WriteLine("\nShark inherits from Animal and Fish. See the shark do things:");
            Shark shark = new Shark();

            Console.WriteLine(shark.Eat());
            Console.WriteLine(shark.Sleep());
            Console.WriteLine(shark.Move());
            Console.WriteLine(shark.MakeSound());
            Console.WriteLine(shark.BreatheUnderwater());
            Console.WriteLine("Find a school? " + shark.FindASchool(false));
            Console.WriteLine(shark.RespondToDanger());

            Console.WriteLine("\nPachyderms are Animals that can Charge and Roll Around.\n");
            Console.WriteLine("\nRhino inherits from Animal and Pachyderm. See the rhino do things:");
            Rhino rhino = new Rhino();

            Console.WriteLine(rhino.Eat());
            Console.WriteLine(rhino.Sleep());
            Console.WriteLine(rhino.Move());
            Console.WriteLine(rhino.MakeSound());
            Console.WriteLine(rhino.Charge());
            Console.WriteLine(rhino.RollAround());
            Console.WriteLine(rhino.RespondToDanger());

            Console.WriteLine("\nHippo inherits from Animal and Pachyderm. See the hippo do things:");
            Hippo hippo = new Hippo();

            Console.WriteLine(hippo.Eat());
            Console.WriteLine(hippo.Sleep());
            Console.WriteLine(hippo.Move());
            Console.WriteLine(hippo.MakeSound());
            Console.WriteLine(hippo.Charge());
            Console.WriteLine(hippo.RollAround());
            Console.WriteLine(hippo.RespondToDanger());
        }
예제 #59
0
파일: MainTest.cs 프로젝트: yyht/rhino
 public void TestVersion()
 {
     using Rhino r = SetUpClass();
     Assert.IsFalse(string.IsNullOrWhiteSpace(r?.Version), "Rhino did not return a valid version number.");
 }
예제 #60
0
파일: MainTest.cs 프로젝트: yyht/rhino
 public void TestContextInfo()
 {
     using Rhino r = SetUpClass();
     Assert.IsFalse(string.IsNullOrWhiteSpace(r?.ContextInfo), "Rhino did not return any context information.");
 }