public async Task <IEnumerable <T> > ListByFilter(FilterParameters filterParameters) { return(await _context.Set <T>() .AsQueryable() .FilterBy(filterParameters) .ToListAsync()); }
public async Task <IHttpActionResult> GetVehicleMakesAsync(string search, int?page = 1, int pageSize = 5, string sortOrder = "", string sortBy = "") { var filter = new FilterParameters { Search = search }; var sort = new SortParameters { SortBy = sortBy, SortOrder = sortOrder }; var pagep = new PageParameters { Page = (int)page, PageSize = pageSize }; var vmlist = await _vehicleMakeService.GetVehicleMakesAsync(sort, filter, pagep); var makeVMList = AutoMapper.Mapper.Map <IEnumerable <VehicleMakeVM> >(vmlist); return(Ok(new { Data = makeVMList, PaggingInfo = vmlist.GetMetaData() })); }
public async Task <ActionResult <(int currentPage, int totalPages, IEnumerable <Product> Products)> > Get( [FromQuery] string brand, [FromQuery] string name, [FromQuery] List <string> categories = null, [FromQuery] double priceGreatherThen = 1, [FromQuery] double priceLowerThen = 99999999, [FromQuery] int page = 1, [FromQuery] int pageSize = 10 ) { var filters = new FilterParameters( categories, brand ?? "", name ?? "", priceGreatherThen, priceLowerThen ); try { var products = await _repository.FindAll(page, pageSize, filters); return(Ok(new { products.currentPage, products.totalPages, products.data })); } catch (System.Exception) { return(new StatusCodeResult(StatusCodes.Status500InternalServerError)); } }
public void List(long page = 1, Arguments args = null) { string q = Request.QueryString["q"]; FilterParameters filter = new FilterParameters(); filter.Load(page, args); this["Q"] = q; this["Filter"] = filter; this["RecommendList"] = M.Product.GetTopRecommendByCategory(DataSource, 5, 0); this["ProductList"] = M.Product.GetPageBySearch(DataSource, Request.QueryString, filter, page, 20, 8); string requestParam = string.Format("?q={0}&searchType={1}&id={2}", Request.QueryString["q"], Request.QueryString["searchType"], Request.QueryString["id"]); this["PageUrl"] = new FuncHandler((object[] ps) => { return(string.Concat(GetUrl("/search/list", filter.CopyByPage(Convert.ToInt64(ps[0])).ToString()), requestParam)); }); this["BrandUrl"] = new FuncHandler((object[] ps) => { return(string.Concat(GetUrl("/search/list", filter.CopyByBrand(Convert.ToInt32(ps[0])).ToString()), requestParam)); }); this["OrderUrl"] = new FuncHandler((object[] ps) => { return(string.Concat(GetUrl("/search/list", filter.CopyByOrderBy(Convert.ToInt32(ps[0])).ToString()), requestParam)); }); this["AttrUrl"] = new FuncHandler((object[] ps) => { return(string.Concat(GetUrl("/search/list", filter.Copy(Convert.ToInt64(ps[0]), ps[1] as string).ToString()), requestParam)); }); Render("search.html"); }
public ProductWithInvoice GetProductWithInvoice(string barcode, FilterParameters filter) { var itemInfoParameters = new Dictionary <string, object> { { "Barcode", barcode } }; var product = _connection.WithRetry(p => p.QueryFirstOrDefault <Product>("qry_GetB2CItemInfo", Utils.ToDynamicParameters(itemInfoParameters), commandType: CommandType.StoredProcedure)); var invoiceParameters = new Dictionary <string, object> { { "Barcode", barcode }, { "StoreCode", filter.StoreCode }, { "StartDate", filter.StartDate }, { "EndDate", filter.EndDate } }; var invoiceHeader = _connection.WithRetry(p => p.QueryFirstOrDefault <InvoiceHeader>("qry_GetB2CInvoices", Utils.ToDynamicParameters(invoiceParameters), commandType: CommandType.StoredProcedure)); if (string.IsNullOrWhiteSpace(invoiceHeader?.AlisverisID)) { return(new ProductWithInvoice(product, null, null)); } var invoiceLineParameters = new Dictionary <string, object> { { "AlisverisID", invoiceHeader.AlisverisID } }; var invoicesLines = _connection.WithRetry(p => p.Query <InvoiceLine>("qry_GetB2CInvoiceLines", Utils.ToDynamicParameters(invoiceLineParameters), commandType: CommandType.StoredProcedure)); return(new ProductWithInvoice(product, invoiceHeader, invoicesLines)); }
public static ICollection <Call> Filter(this ICollection <Call> calls, FilterParameters param, string value) { ICollection <Call> callList = calls; ICollection <Call> result = new List <Call>(); switch (param) { case FilterParameters.ABONENT: { FilterByAbonent(value, callList, result); break; } case FilterParameters.CALL_DATE: { FilterByDate(value, callList, result); break; } case FilterParameters.COST: { FilterByCost(value, callList, result); break; } } return(result); }
public float[] GetValues(FilterParameters frame) { // training trainingRuns++; if (trainingRuns < 10000) { float target = trainingFilter.GetValues(frame)[(int)BroadbandTransientFilter.Outputs.Edge]; if (target < 0.95f) { target = 0f; } output[(int)Outputs.TrainingTarget] = target; neuralNetwork.LearningRate = target > 0.5f ? 0.05f : 0.01f; avgError = avgError * 0.99f + 0.01f * TrainNetwork(trainingContext, frame.SpectrumDB, target); output[(int)Outputs.Error] = avgError * 4.0f; } else { output[(int)Outputs.TrainingTarget] = 0.5f; output[(int)Outputs.Error] = 0f; } // fill context with current spectrum frame runContext.Set(frame.SpectrumDB.Take(runContext.InputCount)); neuralNetwork.Run(runContext); output[(int)Outputs.Output] = runContext.Outputs.First(); return(output); }
public ICreateFilterExpressions GetFilter(FilterParameters parameters) { var filterType = Type.GetType(String.Format("{0}.{1}Filter", typeof(FilterParameters).Namespace, TypeName), false) ?? Type.GetType(TypeName, true); var filters = Filters.Cast<FilterElement>().Select(element => element.GetFilter(parameters)); return (ICreateFilterExpressions)Activator.CreateInstance(filterType, this, filters); }
//private List<object> CreateMedicationFilter(string personId, string encounterId) private List <object> CreateMedicationFilter(string personId) { string encounterId = ""; string encounterDetails = CheckIfPatientIsAdmitted(personId); if (encounterDetails != "[]" || encounterDetails.IsNotEmpty()) { var enc = JsonConvert.DeserializeObject <List <Dictionary <string, dynamic> > >(encounterDetails); foreach (var item in enc) { if (item.ContainsKey("encounter_id")) { encounterId = item["encounter_id"]; } } } Filter filter = new Filter(); filter.filterClause = "person_id = @person_id and encounter_id = @encounter_id " + "and prescriptionstatus_id = 'fd8833de-213b-4570-8cc7-67babfa31393' and (__medications::text ilike '%paracetamol%' or __medications::text ilike '%\"isantimicrobial\":true%')"; Filters filters = new Filters(); filters.filters.Add(filter); FilterParameter personIdParameter = new FilterParameter(); personIdParameter.paramName = "person_id"; personIdParameter.paramValue = personId; FilterParameter encounterIdParameter = new FilterParameter(); encounterIdParameter.paramName = "encounter_id"; encounterIdParameter.paramValue = encounterId; FilterParameters filterParameters = new FilterParameters(); filterParameters.filterparams.Add(personIdParameter); filterParameters.filterparams.Add(encounterIdParameter); SelectStatement selectStatement = new SelectStatement(); selectStatement.selectstatement = "SELECT prescription_id, person_id, encounter_id, __posology, __medications, __routes, createdby, lastmodifiedon"; OrderByGroupByStatement orderByGroupByStatement = new OrderByGroupByStatement(); orderByGroupByStatement.ordergroupbystatement = "ORDER BY lastmodifiedon desc"; List <object> body = new List <object>(); body.Add(filters); body.Add(filterParameters); body.Add(selectStatement); body.Add(orderByGroupByStatement); return(body); }
public float[] GetValues(FilterParameters frame) { float current = 0f; for (int i = freqStart; i < freqStart + freqCount; i++) { current += frame.Spectrum[i]; } current /= (float)freqCount; current = current.NormDB(); output[0] = current; avg = avg * lowpassCoeff + current * (1f - lowpassCoeff); output[1] = avg; avg = Math.Max(0.3f, avg); output[2] = Math.Max(0f, (current - avg) * 4.0f); activation += Decay; activation = Math.Min(1f, activation); if (output[2] > Threshold && activation > Release) { activation = 0f; } output[3] = 1f - activation; return(output); }
public ICreateFilterExpressions GetFilter(FilterParameters parameters) { var filterType = Type.GetType(String.Format("{0}.{1}Filter", typeof(FilterParameters).Namespace, TypeName), false) ?? Type.GetType(TypeName, true); var filters = Filters.Cast <FilterElement>().Select(element => element.GetFilter(parameters)); return((ICreateFilterExpressions)Activator.CreateInstance(filterType, this, filters)); }
/// <summary> /// Get method, /// /api/VehicleMake/?page=&pagesize=5&search=&sort=&direction= /// </summary> /// <param name="page">Current page</param> /// <param name="pagesize">Page size, if page size is not given it's set to 0</param> /// <param name="search">Search</param> /// <param name="sort">Sort by Name or Abrv</param> /// <param name="direction">Sort direction it can be ascending or descending</param> /// <returns>Returns a list of VehicleMakeVM</returns> public async Task <IHttpActionResult> Get(int?page, int?pagesize, string search, string sort, string direction) { var sortParameters = new SortParameters() { Sort = sort, SortDirection = direction ?? "Descending" }; var filterParameters = new FilterParameters() { Search = search }; var pageParameters = new PageParameters() { Page = page ?? 1, /*I set the page size to 0, because as you can see in VehicleMakeService when page size is set to 0 it skips pagging. * Because in one case I need to get all of thevehicle makes. * Example is in angular part when I need to get all VehicleMakes when I'm creating a new VehicleModel, * it needs VehicleMakeId to be created. * So a drop down menu with all Vehicle Makes can be created from which VehicleMakeId can be chosen from. */ PageSize = pagesize ?? 0 }; var vehicleMakeListPaged = AutoMapper.Mapper.Map <IPagedResult <VehicleMakeVM> >(await service.GetVehicleMakesAsync(sortParameters, filterParameters, pageParameters)); return(Ok(vehicleMakeListPaged)); }
private IEnumerable <ResponseSet> FilterResponseSet(FilterParameters parameters, IEnumerable <ResponseSet> responseSets, Func <ResponseSet, DateTime> criteriaDate) { var resultCollection = new List <ResponseSet>(); switch (parameters.Type) { case FilterType.ByDate: { switch (parameters.Date.SelectedPeriod.Key) { case TimePeriods.After: resultCollection = responseSets.Where(r => criteriaDate(r).Date > parameters.Date.SelectedDate.Date).ToList(); break; case TimePeriods.At: resultCollection = responseSets.Where(r => criteriaDate(r).Date == parameters.Date.SelectedDate.Date).ToList(); break; case TimePeriods.Before: resultCollection = responseSets.Where(r => criteriaDate(r).Date < parameters.Date.SelectedDate.Date).ToList(); break; case TimePeriods.Between: resultCollection = responseSets.Where(r => criteriaDate(r).Date <= parameters.Date.SelectedEndDate.Date && criteriaDate(r).Date >= parameters.Date.SelectedStartDate.Date).ToList(); break; } ; } break; } return(resultCollection); }
private async Task <object> GetSeedData() { using (HttpClient httpClient = new HttpClient()) { if (System.Diagnostics.Debugger.IsAttached == false) { System.Diagnostics.Debugger.Launch(); } var payload = new FilterParameters(); payload.filter = new Filter(); string json = JsonConvert.SerializeObject(payload); var response = httpClient.PostAsync(twoTapHelper.TwoTapURLCreator("filters"), new StringContent(json, Encoding.UTF8, "application/json")).Result; var responseContent = await response.Content.ReadAsStringAsync(); // Trying to deserialize on type of FIlter source. This is not universal var list = JsonConvert.DeserializeObject <FilterSource>(responseContent); try { list.PopulateFilters(); } catch (Exception e) { Debug.WriteLine(e.ToString()); } return(responseContent); } }
public async Task <IHttpActionResult> GetVehicleModelsAsync(string search, int?makeId, string sortOrder = "", int?page = 1, int pageSize = 5, string sortBy = "") { var filter = new FilterParameters { Search = search, MakeId = makeId }; var sort = new SortParameters { SortBy = sortBy, SortOrder = sortOrder }; var pagep = new PageParameters { Page = (int)page, PageSize = pageSize, }; var vmlist = await _vehicleModelService.GetVehicleModelsAsync(sort, filter, pagep); return(Ok(new { Data = vmlist, PaggingInfo = vmlist.GetMetaData() })); }
private int GetTotalNumberOfCurrentItemsByOrganization(FilterParameters filter, Models.Register register) { var totalNumberOfItems = 0; if (register.IsInspireStatusRegister() || register.IsMareanoStatusRegister() || register.IsGeodatalovStatusRegister()) { if (!string.IsNullOrEmpty(filter.filterOrganization)) { return(register.RegisterItems.Where(o => o.Owner.seoname.ToLower() == filter.filterOrganization.ToLower()).Count()); } else { return(register.RegisterItems.Count); } } if (filter?.filterOrganization != null) { Models.Organization organization = _registerItemService.GetOrganizationByFilterOrganizationParameter(filter.filterOrganization); totalNumberOfItems = register.NumberOfCurrentVersions(organization); } else { totalNumberOfItems = register.NumberOfCurrentVersions(); } return(totalNumberOfItems); }
internal JsonResult Filter(FilterParameters param) { IList <SubletModel> sm = new List <SubletModel>(); if (param.Tags.Any()) { foreach (var tag in param.Tags) { foreach (var sub in _context.TagIndex.Where(s => s.Tag.Equals(tag))) { sm.Add(GetSublet(sub.ID)); } } foreach (var sublet in sm.ToList()) { if (sublet == null) { sm.Remove(sublet); continue; } if (param.Tags.Except(GetSubletTags(sublet.ID)).Any()) { sm.Remove(sublet); } } if (!sm.Any()) { return(new JsonResult(new List <SubletModel>())); } } else { sm = GetSublets(); } foreach (var sub in _context.Sublets.Where(s => (s.Price <param.MinPrice || s.Price> param.MaxPrice) || (s.Rating <param.MinRating || s.Rating> param.MaxRating))) { sm.Remove(sub); } if (param.IsFurnished == 1) { foreach (var sub in _context.SubletData.Where(s => s.IsFurnished == false)) { sm.Remove(GetSublet(sub.SubletID)); } } else if (param.IsFurnished == 0) { foreach (var sub in _context.SubletData.Where(s => s.IsFurnished == true)) { sm.Remove(GetSublet(sub.SubletID)); } } return(new JsonResult(sm)); }
public virtual async Task <IEnumerable <TDataTransfer> > ListByFilter( FilterParameters filterParameters, ClaimsPrincipal user = null) { var entityList = await Repository.ListByFilter(filterParameters); return(Mapper.Map <IEnumerable <TDataTransfer> >(entityList)); }
/// <summary> /// Gets a querable collection of type "E" with the specified parameters. /// </summary> /// <typeparam name="E">Entity type contained in class.</typeparam> /// <param name="request">Request with the specified parameters.</param> /// <param name="input">This is the input to apply the query.</param> /// <returns></returns> public static IQueryable <E> GetData <E>(this IQueryable <E> input, QueryParameters request) //where E : class, new() { var filterParameters = FilterParameters.GetFilterExpression <E>(request.FilterCollection); var result = input.GetData <E>(filterParameters.FilterExpression, string.Join(' ', request.SortingNames), request.PageIndex, request.RecordsCount, filterParameters.Parameters); return(result); }
public DynamicFilterExpression(IFilterMessages filter) { Verify.NotNull(filter, "filter"); staticFilter = filter; systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); filterParameters = new FilterParameters { systemEvent }; }
/// <summary> /// Add new parameter and get it's name /// </summary> /// <param name="value"></param> /// <returns></returns> public string AddParameter(object value) { var name = $"{ParametersPrefix}{FilterParameters.Count + 1}"; FilterParameters.Add(name, value); return(name); }
static WithStaticFilterDefinition() { var systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); var filterParameters = new FilterParameters { systemEvent }; var expression = new AndAlsoFilter(new FakeExtendedProperties(), Enumerable.Empty<ICreateFilterExpressions>()).CreateExpression(filterParameters); StaticFilter = new StaticFilterExpression(systemEvent, expression); }
public JsonResult Filter([FromBody] FilterParameters param) { if (!ModelState.IsValid) { return(Json("Model state is invalid")); } return(_subletRepo.Filter(param)); }
protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) { int pageSize = Int32.MaxValue; if (arguments.MaximumRows > 0) { pageSize = arguments.MaximumRows; } int pageIndex = (arguments.StartRowIndex / pageSize); PageRequest request = null; if (!(String.IsNullOrEmpty(_owner.PageRequestParameterName))) { string r = HttpContext.Current.Request.Params[_owner.PageRequestParameterName]; if (!(String.IsNullOrEmpty(r))) { #pragma warning disable 0618 System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); #pragma warning restore 0618 request = serializer.Deserialize <PageRequest>(r); request.PageIndex = pageIndex; request.PageSize = pageSize; request.View = _owner.DataView; } } if (request == null) { request = new PageRequest(pageIndex, pageSize, arguments.SortExpression, null); List <string> filter = new List <string>(); System.Collections.Specialized.IOrderedDictionary filterValues = FilterParameters.GetValues(HttpContext.Current, _owner); foreach (Parameter p in FilterParameters) { if (filterValues[p.Name] != null) { string query = (p.Name + ":"); foreach (string s in Convert.ToString(filterValues[p.Name]).Split(',', ';')) { string q = Controller.ConvertSampleToQuery(s); if (!(String.IsNullOrEmpty(q))) { query = (query + q); } } filter.Add(query); } } request.Filter = filter.ToArray(); } request.RequiresMetaData = true; request.RequiresRowCount = arguments.RetrieveTotalRowCount; ViewPage page = ControllerFactory.CreateDataController().GetPage(_dataController, _dataView, request); if (arguments.RetrieveTotalRowCount) { arguments.TotalRowCount = page.TotalRowCount; } return(page.ToDataTable().DefaultView); }
public virtual IQueryable <TModel> GetAll(FilterParameters filter = null) { var entities = (filter == null || filter.PageNumber == default || filter.PageSize == default) ? DbSet : DbSet.Skip((filter.PageNumber - 1) * filter.PageSize) .Take(filter.PageSize); var models = Сonverter.ConvertTo(entities); return(models.AsQueryable()); }
public Result(FilterParameters filter, int count) { if (filter != null) { Offset = filter.Offset; Limit = filter.Limit; } Count = count; }
public async Task <IEnumerable <T> > ListByFilter(FilterParameters filterParameters, params Expression <Func <T, object> >[] includeProperties) { var query = includeProperties .Aggregate(_context.Set <T>().AsQueryable(), (current, property) => current.Include(property)); return(await query .FilterBy(filterParameters) .ToListAsync()); }
static WithStaticFilterDefinition() { var systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); var filterParameters = new FilterParameters { systemEvent }; var expression = new AndAlsoFilter(new FakeExtendedProperties(), Enumerable.Empty <ICreateFilterExpressions>()).CreateExpression(filterParameters); StaticFilter = new StaticFilterExpression(systemEvent, expression); }
public void ReturnTrueIfFilterExpressionIsNotSatisfied() { var extendedProperties = new FakeExtendedProperties { { "property", "Level" }, { "value", "Fatal" } }; var systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); var filterParameters = new FilterParameters { systemEvent }; var filter = new StaticFilterExpression(systemEvent, new EqualFilter(extendedProperties, Enumerable.Empty<ICreateFilterExpressions>()).CreateExpression(filterParameters)); Assert.True(filter.Exclude(new SystemEvent { Level = SystemEventLevel.Error })); }
public Dictionary <DateTime, int> EventLogForRig(Bridge.EventType eventType, FilterParameters filterParameters) { ReportDaoManager daoManager = new ReportDaoManager(); Dictionary <DateTime, int> result = daoManager.GetEventLogByEvent(eventType, filterParameters); Console.WriteLine($"Accessing EventLogforRig: {result.Count.ToString()} records returned."); Console.WriteLine($"FilterParams: startDate ={filterParameters.StartDate} stopDate={filterParameters.StopDate} groupby={filterParameters.WithGrouping.ToString()}"); return(result); }
public IFilterMessages CompileFilter() { var systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); var filterParameters = new FilterParameters { systemEvent }; var filters = Filters.Cast <FilterElement>().Select(element => element.GetFilter(filterParameters)); return(new StaticFilterExpression(systemEvent, new AndAlsoFilter(this, filters).CreateExpression(filterParameters))); }
public static bool IsValid(this FilterParameters candidate, out IEnumerable <string> errors) { var validator = new FilterParametersValidator(); var validationResult = validator.Validate(candidate); errors = AggregateErrors(validationResult); return(validationResult.IsValid); }
protected override Expression BuildExpression(FilterParameters parameters) { var systemEvent = parameters.GetParameter(typeof(SystemEvent)); var propertyName = ExtendedProperties.GetExtendedProperty("property"); var propertyExpression = Expression.Property(systemEvent, propertyName); return expressionBuilder.Invoke( ConvertPropertyValueIfRequired(propertyExpression), GetConvertedValue(propertyExpression.Type) ); }
/// <summary> /// Filters Novads list /// </summary> public IEnumerable <Novads> FilterNovadsList(FilterParameters filterParams) { List <Novads> novadsList = _repository.GetAllNovadsLoadedReadOnly(); foreach (var novads in novadsList) { novads.PagastsList = this.FilterPagastsList(novads.Id, filterParams).ToList(); } return(novadsList.Where(novads => novads.PagastsList.Count > 0).ToList()); }
public IQueryable <T> FindAllPaging(FilterParameters <T> parameters) { IQueryable <T> listaAPaginar = GetListContext().Where(parameters.WhereFilter); dynamic orderBy = Helper.LambdaPropertyOrderBy <T>(parameters.ColumnOrder); listaAPaginar = (parameters.OrderType == TipoOrden.Asc) ? Queryable.OrderBy(listaAPaginar, orderBy) : Queryable.OrderByDescending(listaAPaginar, orderBy); return(listaAPaginar.Skip(parameters.Start).Take(parameters.AmountRows)); }
public static Func<SystemEvent, Boolean> Compile(ICreateFilterExpressions filter) { var systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); var filterParameters = new FilterParameters { systemEvent }; var expression = filter.CreateExpression(filterParameters); Trace.WriteLine(expression); return Expression.Lambda<Func<SystemEvent, Boolean>>( filter.CreateExpression(filterParameters), systemEvent ).Compile(); }
protected override Expression BuildExpression(FilterParameters parameters) { var filters = Children.ToList(); switch (filters.Count) { case 0: return Expression.Constant(true); case 1: return filters[0].CreateExpression(parameters); default: var expression = filters[0].CreateExpression(parameters); for (var i = 1; i < filters.Count; i++) expression = expressionBuilder.Invoke(expression, filters[i].CreateExpression(parameters)); return expression; } }
public IFilterMessages CompileFilter() { var systemEvent = Expression.Parameter(typeof(SystemEvent), "e"); var filterParameters = new FilterParameters { systemEvent }; var filters = Filters.Cast<FilterElement>().Select(element => element.GetFilter(filterParameters)); return new StaticFilterExpression(systemEvent, new AndAlsoFilter(this, filters).CreateExpression(filterParameters)); }
protected override Expression BuildExpression(FilterParameters parameters) { return Expression.Not(base.BuildExpression(parameters)); }
static IQueryable<TestBrowse.Source> FilterSource(IQueryable<TestBrowse.Source> source, FilterParameters parameters) { return source.Where(item => parameters.Code == null || parameters.Code == item.Code && parameters.RefID == "00000000-0000-0000-0000-000000000000" || new Guid(parameters.RefID) == item.Ref.ID); }
public Expression CreateExpression(FilterParameters parameters) { Verify.NotNull(parameters, "parameters"); return BuildExpression(parameters); }
private void Apply3D(Vector3 listenerForward, Vector3 listenerUp, Vector3 listenerPosition, Vector3 listenerVelocity, Vector3 emitterForward, Vector3 emitterUp, Vector3 emitterPosition, Vector3 emitterVelocity) { if (!Effect.AudioManager.IsSpatialAudioEnabled) throw new InvalidOperationException("Spatial audio must be enabled first."); if (emitter == null) emitter = new Emitter(); emitter.OrientFront = emitterForward; emitter.OrientTop = emitterUp; emitter.Position = emitterPosition; emitter.Velocity = emitterVelocity; emitter.DopplerScaler = SoundEffect.DopplerScale; emitter.CurveDistanceScaler = SoundEffect.DistanceScale; emitter.ChannelCount = Effect.Format.Channels; //TODO: work out what ChannelAzimuths is supposed to be. if (emitter.ChannelCount > 1) emitter.ChannelAzimuths = new float[emitter.ChannelCount]; if (listener == null) listener = new Listener(); listener.OrientFront = listenerForward; listener.OrientTop = listenerUp; listener.Position = listenerPosition; listener.Velocity = listenerVelocity; if (dspSettings == null) dspSettings = new DspSettings(Effect.Format.Channels, Effect.AudioManager.MasteringVoice.VoiceDetails.InputChannelCount); CalculateFlags flags = CalculateFlags.Matrix | CalculateFlags.Doppler | CalculateFlags.LpfDirect; if ((Effect.AudioManager.Speakers & Speakers.LowFrequency) > 0) { // On devices with an LFE channel, allow the mono source data to be routed to the LFE destination channel. flags |= CalculateFlags.RedirectToLfe; } if (Effect.AudioManager.IsReverbEffectEnabled) { flags |= CalculateFlags.Reverb | CalculateFlags.LpfReverb; if (!isReverbSubmixEnabled) { VoiceSendFlags sendFlags = Effect.AudioManager.IsReverbFilterEnabled ? VoiceSendFlags.UseFilter : VoiceSendFlags.None; VoiceSendDescriptor[] outputVoices = new VoiceSendDescriptor[] { new VoiceSendDescriptor { OutputVoice = Effect.AudioManager.MasteringVoice, Flags = sendFlags }, new VoiceSendDescriptor { OutputVoice = Effect.AudioManager.ReverbVoice, Flags = sendFlags } }; voice.SetOutputVoices(outputVoices); isReverbSubmixEnabled = true; } } Effect.AudioManager.Calculate3D(listener, emitter, flags, dspSettings); voice.SetFrequencyRatio(dspSettings.DopplerFactor); voice.SetOutputMatrix(Effect.AudioManager.MasteringVoice, dspSettings.SourceChannelCount, dspSettings.DestinationChannelCount, dspSettings.MatrixCoefficients); if (Effect.AudioManager.IsReverbEffectEnabled) { if (reverbLevels == null || reverbLevels.Length != Effect.Format.Channels) reverbLevels = new float[Effect.Format.Channels]; for (int i = 0; i < reverbLevels.Length; i++) { reverbLevels[i] = dspSettings.ReverbLevel; } voice.SetOutputMatrix(Effect.AudioManager.ReverbVoice, Effect.Format.Channels, 1, reverbLevels); } if (Effect.AudioManager.IsReverbFilterEnabled) { FilterParameters filterDirect = new FilterParameters { Type = FilterType.LowPassFilter, // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here Frequency = 2.0f * (float)Math.Sin(X3DAudio.PI / 6.0f * dspSettings.LpfDirectCoefficient), OneOverQ = 1.0f }; voice.SetOutputFilterParameters(Effect.AudioManager.MasteringVoice, filterDirect); if (Effect.AudioManager.IsReverbEffectEnabled) { FilterParameters filterReverb = new FilterParameters { Type = FilterType.LowPassFilter, // see XAudio2CutoffFrequencyToRadians() in XAudio2.h for more information on the formula used here Frequency = 2.0f * (float)Math.Sin(X3DAudio.PI / 6.0f * dspSettings.LpfReverbCoefficient), OneOverQ = 1.0f }; voice.SetOutputFilterParameters(Effect.AudioManager.ReverbVoice, filterReverb); } } }
protected abstract Expression BuildExpression(FilterParameters parameters);
public static SixenseStatus SetFilterParameters(FilterParameters filters) { return sixenseSetFilterParams(filters.NearRange, filters.NearValue, filters.FarRange, filters.FarValue) == (int)SixenseStatus.SIXENSE_SUCCESS ? SixenseStatus.SIXENSE_SUCCESS : SixenseStatus.SIXENSE_FAILURE; }