Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
582c1c6468 | ||
|
|
192836a763 | ||
|
|
5539048c54 | ||
|
|
843b52b468 | ||
|
|
1487957ea4 | ||
|
|
daf517bc6a | ||
|
|
c45b14d35a | ||
|
|
4734c0f7b7 | ||
|
|
0272fb770e | ||
|
|
0b357be701 | ||
|
|
de8a4b8360 | ||
|
|
83dc34fb53 | ||
|
|
8a306727a7 | ||
|
|
3a2eadad70 | ||
|
|
6017db7599 | ||
|
|
bc29648790 | ||
|
|
0ba90a0bb2 | ||
|
|
3ec70113e6 | ||
|
|
0c3b968aee | ||
|
|
b7514953a6 | ||
|
|
0483420af2 | ||
|
|
a72613aa58 | ||
|
|
b45311404c | ||
|
|
df19ff4b14 | ||
|
|
fa6f76ba7d | ||
|
|
5aee1eb084 |
Vendored
+1
-1
@@ -59,7 +59,7 @@ node {
|
||||
|
||||
// deploy the build output on the server
|
||||
stage ('Deploy') {
|
||||
// release = true; // uncomment to temporary enable snapshot deployments
|
||||
//release = true; // uncomment to temporary enable snapshot deployments
|
||||
if (env.BRANCH_NAME == "master" && release) {
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "keyfile")]) {
|
||||
sh "scp -i ${keyfile} site-ear/build/libs/site-ear-${version}.ear wildfly@apps.nes.uni-due.de:/opt/wildfly-17-mowesta/standalone/deployments/mowesta.ear"
|
||||
|
||||
@@ -88,7 +88,7 @@ android {
|
||||
applicationId "com.mowesta.android.app"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 29
|
||||
versionCode 7
|
||||
versionCode 9
|
||||
versionName "${version}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
@@ -6,8 +6,6 @@ import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.net.NetworkInfo;
|
||||
import android.net.wifi.WifiConfiguration;
|
||||
import android.net.wifi.WifiInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.util.Log;
|
||||
@@ -55,7 +53,7 @@ public class WifiTask extends NetworkTask {
|
||||
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
|
||||
Log.d(TAG, "Received network state changed.");
|
||||
if (intent.hasExtra(WifiManager.EXTRA_NETWORK_INFO)) {
|
||||
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
|
||||
android.net.NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
|
||||
if (info != null) {
|
||||
Log.d(TAG, "Received network info: " + info);
|
||||
if (info.isConnected() && isWifiConnected()) {
|
||||
@@ -119,7 +117,7 @@ public class WifiTask extends NetworkTask {
|
||||
Log.d(TAG, "Wifi was disabled, turning it on.");
|
||||
didEnableWifi = manager.setWifiEnabled(true);
|
||||
}
|
||||
WifiConfiguration existing = findConfiguration();
|
||||
android.net.wifi.WifiConfiguration existing = findConfiguration();
|
||||
if (existing == null) {
|
||||
networkId = manager.addNetwork(createConfiguration());
|
||||
manager.saveConfiguration();
|
||||
@@ -171,8 +169,8 @@ public class WifiTask extends NetworkTask {
|
||||
*/
|
||||
private int getMaximumPriority() throws SecurityException {
|
||||
int result = 1;
|
||||
List<WifiConfiguration> configurations = manager.getConfiguredNetworks();
|
||||
for (WifiConfiguration configuration: configurations) {
|
||||
List<android.net.wifi.WifiConfiguration> configurations = manager.getConfiguredNetworks();
|
||||
for (android.net.wifi.WifiConfiguration configuration: configurations) {
|
||||
result = Math.max(result, configuration.priority);
|
||||
}
|
||||
return result;
|
||||
@@ -184,10 +182,10 @@ public class WifiTask extends NetworkTask {
|
||||
* @return The network configuration, if present already.
|
||||
* @throws SecurityException Thrown if we are missing a permission.
|
||||
*/
|
||||
private WifiConfiguration findConfiguration() throws SecurityException {
|
||||
private android.net.wifi.WifiConfiguration findConfiguration() throws SecurityException {
|
||||
String ssid = getSsid();
|
||||
List<WifiConfiguration> configurations = manager.getConfiguredNetworks();
|
||||
for (WifiConfiguration configuration: configurations) {
|
||||
List<android.net.wifi.WifiConfiguration> configurations = manager.getConfiguredNetworks();
|
||||
for (android.net.wifi.WifiConfiguration configuration: configurations) {
|
||||
if (ssid.equals(configuration.SSID)) {
|
||||
return configuration;
|
||||
}
|
||||
@@ -200,19 +198,19 @@ public class WifiTask extends NetworkTask {
|
||||
*
|
||||
* @return The network configuration.
|
||||
*/
|
||||
private WifiConfiguration createConfiguration() {
|
||||
WifiConfiguration result = new WifiConfiguration();
|
||||
private android.net.wifi.WifiConfiguration createConfiguration() {
|
||||
android.net.wifi.WifiConfiguration result = new android.net.wifi.WifiConfiguration();
|
||||
result.SSID = getSsid();
|
||||
result.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
|
||||
result.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
|
||||
result.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
|
||||
result.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
|
||||
result.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
|
||||
result.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
|
||||
result.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
|
||||
result.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
|
||||
result.allowedAuthAlgorithms.set(android.net.wifi.WifiConfiguration.AuthAlgorithm.OPEN);
|
||||
result.allowedProtocols.set(android.net.wifi.WifiConfiguration.Protocol.RSN); // For WPA2
|
||||
result.allowedKeyManagement.set(android.net.wifi.WifiConfiguration.KeyMgmt.WPA_PSK);
|
||||
result.allowedKeyManagement.set(android.net.wifi.WifiConfiguration.KeyMgmt.WPA_EAP);
|
||||
result.allowedPairwiseCiphers.set(android.net.wifi.WifiConfiguration.PairwiseCipher.TKIP);
|
||||
result.allowedPairwiseCiphers.set(android.net.wifi.WifiConfiguration.PairwiseCipher.CCMP);
|
||||
result.allowedGroupCiphers.set(android.net.wifi.WifiConfiguration.GroupCipher.TKIP);
|
||||
result.allowedGroupCiphers.set(android.net.wifi.WifiConfiguration.GroupCipher.CCMP);
|
||||
result.preSharedKey = String.format("\"%s\"", ArduinoConfig.ARDUINO_PWD);
|
||||
result.status = WifiConfiguration.Status.ENABLED;
|
||||
result.status = android.net.wifi.WifiConfiguration.Status.ENABLED;
|
||||
try {
|
||||
int priority = getMaximumPriority() + 400;
|
||||
Log.d(TAG, "Setting maximum priority to " + priority + ".");
|
||||
|
||||
+19
-13
@@ -58,24 +58,27 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
if (request != null) {
|
||||
switch (request.getType()) {
|
||||
case DAY:
|
||||
pager.setCurrentItem(0, true);
|
||||
break;
|
||||
case TIME:
|
||||
pager.setCurrentItem(1, true);
|
||||
break;
|
||||
case HOUR:
|
||||
case TIME:
|
||||
pager.setCurrentItem(2, true);
|
||||
break;
|
||||
case HOUR:
|
||||
pager.setCurrentItem(3, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
TabLayout tabs = view.findViewById(R.id.tabs);
|
||||
TabLayout tabs = getActivity().findViewById(R.id.tabs);
|
||||
new TabLayoutMediator(tabs, pager, (tab, position) -> {
|
||||
switch (position) {
|
||||
case 0:
|
||||
tab.setText(R.string.city_info_day);
|
||||
tab.setText(R.string.city_info_gradient);
|
||||
break;
|
||||
case 1:
|
||||
tab.setText(R.string.city_info_day);
|
||||
break;
|
||||
case 2:
|
||||
tab.setText(R.string.city_info_time);
|
||||
break;
|
||||
default:
|
||||
@@ -100,16 +103,20 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
@NonNull
|
||||
@Override
|
||||
public Fragment createFragment(int position) {
|
||||
ForecastRecyclerFragment fragment = new ForecastRecyclerFragment();
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putInt("page", position);
|
||||
fragment.setArguments(bundle);
|
||||
return fragment;
|
||||
if (position == 0) {
|
||||
return new CityGradientFragment();
|
||||
} else {
|
||||
ForecastRecyclerFragment fragment = new ForecastRecyclerFragment();
|
||||
Bundle bundle = new Bundle();
|
||||
bundle.putInt("page", position - 1);
|
||||
fragment.setArguments(bundle);
|
||||
return fragment;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return 3;
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,5 +433,4 @@ public class CityForecastFragment extends CityFragment.ChildFragment {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.animation.LinearInterpolator;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.constraintlayout.widget.ConstraintLayout;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.viewpager2.widget.ViewPager2;
|
||||
|
||||
import com.google.android.material.appbar.AppBarLayout;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.FragmentGradientBinding;
|
||||
import com.mowesta.android.app.model.CustomizeViewModel;
|
||||
import com.mowesta.android.app.util.DateFormatter;
|
||||
import com.mowesta.android.app.util.TimeUtils;
|
||||
import com.mowesta.android.app.view.DataView;
|
||||
import com.mowesta.android.app.view.TimeView;
|
||||
import com.mowesta.android.app.view.color.CloudDepthColorScheme;
|
||||
import com.mowesta.android.app.view.color.HumidityColorScheme;
|
||||
import com.mowesta.android.app.view.color.PrecipitationColorScheme;
|
||||
import com.mowesta.android.app.view.color.PressureColorScheme;
|
||||
import com.mowesta.android.app.view.color.ScientificTemperatureColorScheme;
|
||||
import com.mowesta.android.app.view.color.WhiteCloudColorScheme;
|
||||
import com.mowesta.android.feign.model.WeatherCondition;
|
||||
|
||||
/**
|
||||
* The fragment to show the overview as a bunch of gradients.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CityGradientFragment extends CityFragment.ChildFragment {
|
||||
|
||||
/**
|
||||
* The timeout after which we reset the view.
|
||||
*/
|
||||
private static final int TIMEOUT_REMOVER = 10000;
|
||||
|
||||
/**
|
||||
* The view binding.
|
||||
*/
|
||||
private FragmentGradientBinding binding;
|
||||
|
||||
/**
|
||||
* The time utilities.
|
||||
*/
|
||||
private TimeUtils timeUtils = new TimeUtils(System.currentTimeMillis(), null);
|
||||
|
||||
/**
|
||||
* The view pager of the parent.
|
||||
*/
|
||||
private ViewPager2 pager;
|
||||
|
||||
/**
|
||||
* The date formatter.
|
||||
*/
|
||||
private DateFormatter dateFormatter;
|
||||
|
||||
/**
|
||||
* The handler to post the removal of
|
||||
*/
|
||||
private Handler handler = new Handler();
|
||||
|
||||
/**
|
||||
* The animator for the progress bar.
|
||||
*/
|
||||
private ValueAnimator animator;
|
||||
|
||||
/**
|
||||
* The weather condition to display as text.
|
||||
*/
|
||||
private WeatherCondition condition = new WeatherCondition();
|
||||
|
||||
private boolean closed = false;
|
||||
|
||||
private Runnable remover = () -> {
|
||||
updateSelection(null);
|
||||
animator.cancel();
|
||||
binding.gradientText.setVisibility(View.GONE);
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
dateFormatter = new DateFormatter(getContext());
|
||||
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_gradient, container, false);
|
||||
// this is quite ugly, but we need to disable the view pager and collapse the toolbar
|
||||
pager = getActivity().findViewById(R.id.pager);
|
||||
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
|
||||
binding.gradientProgress1.setMax(TIMEOUT_REMOVER);
|
||||
binding.gradientProgress2.setMax(TIMEOUT_REMOVER);
|
||||
animator = ValueAnimator.ofInt(TIMEOUT_REMOVER, 0);
|
||||
animator.setInterpolator(new LinearInterpolator());
|
||||
animator.setDuration(TIMEOUT_REMOVER);
|
||||
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
|
||||
@Override
|
||||
public void onAnimationUpdate(ValueAnimator animation){
|
||||
int value = (Integer)animation.getAnimatedValue();
|
||||
binding.gradientProgress1.setProgress(value);
|
||||
binding.gradientProgress2.setProgress(value);
|
||||
binding.gradientText.setAlpha(Math.min(1, Math.max(0, value / 1000f)));
|
||||
}
|
||||
});
|
||||
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
|
||||
@Override
|
||||
public void onSlide(float relative) {
|
||||
if (!hasData()) return;
|
||||
animator.cancel();
|
||||
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
|
||||
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
|
||||
binding.gradientText.setAlpha(1);
|
||||
handler.removeCallbacks(remover);
|
||||
if (!closed) {
|
||||
layout.setExpanded(false, true);
|
||||
closed = true;
|
||||
}
|
||||
pager.setUserInputEnabled(false);
|
||||
updateSelection(relative);
|
||||
updateCondition(relative);
|
||||
binding.gradientText.setVisibility(View.VISIBLE);
|
||||
updateGuide(relative);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSlideEnd() {
|
||||
pager.setUserInputEnabled(true);
|
||||
closed = false;
|
||||
animator.start();
|
||||
handler.postDelayed(remover, TIMEOUT_REMOVER);
|
||||
}
|
||||
}));
|
||||
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.gradientText.setVisibility(View.GONE);
|
||||
binding.gradientTemperature.setColorScheme(new ScientificTemperatureColorScheme());
|
||||
binding.gradientCloud.setColorScheme(new WhiteCloudColorScheme());
|
||||
binding.gradientCloud.setSecondaryColorScheme(new CloudDepthColorScheme());
|
||||
binding.gradientPreciptiation.setColorScheme(new PrecipitationColorScheme());
|
||||
binding.gradientHumidity.setColorScheme(new HumidityColorScheme());
|
||||
getCityViewModel().getHour().observe(getViewLifecycleOwner(), (list) -> {
|
||||
if (list == null) return;
|
||||
int housrs = 0;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
housrs += list.get(i).getCondition().getValue().getDuration();
|
||||
}
|
||||
Double[] temp = new Double[housrs];
|
||||
Double[] cloud = new Double[housrs];
|
||||
Double[] depth = new Double[housrs];
|
||||
Double[] prec = new Double[housrs];
|
||||
Double[] pres = new Double[housrs];
|
||||
Double[] wind = new Double[housrs];
|
||||
Double[] hum = new Double[housrs];
|
||||
Long[] hours = new Long[housrs];
|
||||
int index = 0;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
WeatherCondition wc = list.get(i).getCondition().getValue();
|
||||
for (int j = 0; j < wc.getDuration(); j++) {
|
||||
temp[index] = wc.getTemperature();
|
||||
cloud[index] = wc.getCloudCoverage();
|
||||
prec[index] = wc.getPrecipitation();
|
||||
pres[index] = wc.getPressure();
|
||||
depth[index] = wc.getCloudDepth();
|
||||
wind[index] = wc.getWindSpeed();
|
||||
hum[index] = wc.getHumidity();
|
||||
hours[index] = wc.getTime() + j * 3600000;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
binding.gradientCloud.setSecondaryData(depth);
|
||||
binding.gradientTemperature.setData(temp);
|
||||
binding.gradientPressure.setData(pres);
|
||||
binding.gradientCloud.setData(cloud);
|
||||
binding.gradientPreciptiation.setData(prec);
|
||||
binding.gradientWindSpeed.setData(wind);
|
||||
binding.gradientHumidity.setData(hum);
|
||||
binding.gradientTouch.setData(hours);
|
||||
});
|
||||
getCityViewModel().getForecast().observe(getViewLifecycleOwner(), (forecast) -> {
|
||||
if (forecast != null) {
|
||||
// 1013,25 hPa * [ 1 − 6,5 * Höhe / (288150 m) ]5,255
|
||||
double avg = 1013.25 * Math.pow(1 - 6.5 * forecast.getSurfaceHeight() / 288150.0, 5.255);
|
||||
binding.gradientPressure.setColorScheme(new PressureColorScheme(avg, avg - 20, avg + 10));
|
||||
}
|
||||
});
|
||||
getCityViewModel().getCity().observe(getViewLifecycleOwner(), (city) -> {
|
||||
if (city != null) {
|
||||
binding.gradientTouch.setTimezone(city.getTimezone());
|
||||
timeUtils = new TimeUtils(System.currentTimeMillis(), city.getTimezone());
|
||||
}
|
||||
});
|
||||
// observe changes to the settings that affect us
|
||||
CustomizeViewModel customizeViewModel = new ViewModelProvider(this).get(CustomizeViewModel.class);
|
||||
customizeViewModel.getTemperatureUnit().observe(getViewLifecycleOwner(), (u)-> {
|
||||
Float selection = binding.gradientTouch.getSelection();
|
||||
if (selection != null) updateCondition(selection);
|
||||
});
|
||||
customizeViewModel.getUnitSystem().observe(getViewLifecycleOwner(), (s) -> {
|
||||
Float selection = binding.gradientTouch.getSelection();
|
||||
if (selection != null) updateCondition(selection);
|
||||
});
|
||||
|
||||
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
private boolean hasData() {
|
||||
return binding.gradientTouch.getData() != null && binding.gradientTouch.getData().length > 0;
|
||||
}
|
||||
|
||||
private void updateSelection(Float selection) {
|
||||
binding.gradientTemperature.setSelection(selection);
|
||||
binding.gradientWindSpeed.setSelection(selection);
|
||||
binding.gradientPreciptiation.setSelection(selection);
|
||||
binding.gradientHumidity.setSelection(selection);
|
||||
binding.gradientPressure.setSelection(selection);
|
||||
binding.gradientCloud.setSelection(selection);
|
||||
binding.gradientTouch.setSelection(selection);
|
||||
}
|
||||
|
||||
private void updateCondition(float selection) {
|
||||
long time = binding.gradientTouch.getDataAt(selection);
|
||||
condition.setTime(time);
|
||||
condition.setWindSpeed(binding.gradientWindSpeed.getDataAt(selection));
|
||||
condition.setPrecipitation(binding.gradientPreciptiation.getDataAt(selection));
|
||||
condition.setHumidity(binding.gradientHumidity.getDataAt(selection));
|
||||
condition.setPressure(binding.gradientPressure.getDataAt(selection));
|
||||
condition.setCloudCoverage(binding.gradientCloud.getDataAt(selection));
|
||||
condition.setTemperature(binding.gradientTemperature.getDataAt(selection));
|
||||
String day = timeUtils.getDayName(getContext(), time);
|
||||
String hour = dateFormatter.asTime(time, binding.gradientTouch.getTimezone());
|
||||
binding.gradientTime.setText(getString(R.string.format_two_parts, day, hour));
|
||||
binding.setModel(condition);
|
||||
}
|
||||
|
||||
private void updateGuide(float relative) {
|
||||
float px = 64 * getResources().getDisplayMetrics().density;
|
||||
float max = 128 * getResources().getDisplayMetrics().density;
|
||||
int size = binding.gradientTouch.getDirection() == DataView.Direction.HORIZONTAL ?
|
||||
binding.gradientConstraint.getWidth():binding.gradientConstraint.getHeight();
|
||||
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams)binding.gradientText.getLayoutParams();
|
||||
float percent = size == 0 ? 0 : px / size;
|
||||
float delta = size == 0 ? 0 : max / size;
|
||||
if (binding.gradientTouch.getDirection() == DataView.Direction.VERTICAL) {
|
||||
if (relative - delta < 0) {
|
||||
binding.guideGradient.setGuidelinePercent(relative + 2 * percent);
|
||||
params.bottomToTop = -1;
|
||||
params.topToBottom = R.id.guide_gradient;
|
||||
} else {
|
||||
binding.guideGradient.setGuidelinePercent(relative - percent);
|
||||
params.topToBottom = -1;
|
||||
params.bottomToTop = R.id.guide_gradient;
|
||||
}
|
||||
|
||||
} else {
|
||||
if (relative > 0.5) {
|
||||
binding.guideGradient.setGuidelinePercent(relative - percent);
|
||||
params.leftToLeft = -1;
|
||||
params.rightToRight = R.id.guide_gradient;
|
||||
} else {
|
||||
binding.guideGradient.setGuidelinePercent(relative + percent);
|
||||
params.leftToLeft = R.id.guide_gradient;
|
||||
params.rightToRight = -1;
|
||||
}
|
||||
}
|
||||
binding.gradientText.setLayoutParams(params);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
handler.removeCallbacks(remover);
|
||||
remover.run();
|
||||
super.onPause();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,16 @@ public class LoginFragment extends Fragment {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_devices, null, b.build());
|
||||
break;
|
||||
case COLLECTION:
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
|
||||
try {
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.action_login_collection);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// this is most likely bug in the navigation library, since it cannot find the
|
||||
// node in the xml file which is technically impossible (probably a race during loading)
|
||||
NavOptions.Builder builder = new NavOptions.Builder().setPopUpTo(R.id.destination_login, true);
|
||||
builder.setEnterAnim(R.anim.slide_in_right);
|
||||
builder.setExitAnim(R.anim.slide_out_left);
|
||||
Navigation.findNavController(binding.getRoot()).navigate(R.id.destination_collection, null, builder.build());
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@ public class SetupViewModel extends AndroidViewModel {
|
||||
}
|
||||
}
|
||||
@Override
|
||||
@SuppressWarnings("deprecation")
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) { }
|
||||
@Override
|
||||
public void onProviderEnabled(String provider) { }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.mowesta.android.app.util;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
@@ -38,8 +39,8 @@ public class DateFormatter {
|
||||
* @return The formatted date with time.
|
||||
*/
|
||||
public String asDateTime(long time, @Nullable String timezone) {
|
||||
Date date = getDate(time, timezone);
|
||||
return getDateFormat().format(date) + " " + getTimeFormat().format(date);
|
||||
Calendar date = getDate(time, timezone);
|
||||
return format(getDateFormat(), date) + " " + format(getTimeFormat(), date);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,7 +51,7 @@ public class DateFormatter {
|
||||
* @return The formatted date.
|
||||
*/
|
||||
public String asDate(long time, @Nullable String timezone) {
|
||||
return getDateFormat().format(getDate(time, timezone));
|
||||
return format(getDateFormat(), getDate(time, timezone));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,7 +62,7 @@ public class DateFormatter {
|
||||
* @return The formatted time.
|
||||
*/
|
||||
public String asTime(long time, @Nullable String timezone) {
|
||||
return getTimeFormat().format(getDate(time, timezone));
|
||||
return format(getTimeFormat(), getDate(time, timezone));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,13 +72,26 @@ public class DateFormatter {
|
||||
* @param timezone The timezone or null to use the host timezone.
|
||||
* @return The date.
|
||||
*/
|
||||
private Date getDate(long time, @Nullable String timezone) {
|
||||
private Calendar getDate(long time, @Nullable String timezone) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
if (timezone != null) {
|
||||
c.setTimeZone(TimeZone.getTimeZone(timezone));
|
||||
|
||||
}
|
||||
c.setTimeInMillis(time);
|
||||
return c.getTime();
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the time in the calendar using the format.
|
||||
*
|
||||
* @param format The format.
|
||||
* @param c The calendar.
|
||||
* @return The string.
|
||||
*/
|
||||
private String format(DateFormat format, Calendar c) {
|
||||
format.setCalendar(c);
|
||||
return format.format(c.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package com.mowesta.android.app.view;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
|
||||
/**
|
||||
* A base class for views that show data. Besides from storing the
|
||||
* values this view also contains some funky logic to create a
|
||||
* magnifier effect.
|
||||
*
|
||||
* @param <T> The type of data to display.
|
||||
*/
|
||||
public abstract class DataView<T> extends View {
|
||||
|
||||
|
||||
/** The drawing direction of the gradient. */
|
||||
public enum Direction {
|
||||
/** Draw from left to right. */
|
||||
HORIZONTAL,
|
||||
/** Draw from top to bottom. */
|
||||
VERTICAL;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The drawing direction.
|
||||
*/
|
||||
@NonNull
|
||||
protected Direction direction = Direction.VERTICAL;
|
||||
|
||||
/**
|
||||
* A bitmap to draw the magnifier effect.
|
||||
*/
|
||||
protected Bitmap bitmap;
|
||||
|
||||
/**
|
||||
* The bitmap size in dp.
|
||||
*/
|
||||
protected int bitmapSize;
|
||||
|
||||
/**
|
||||
* The data of the view.
|
||||
*/
|
||||
@Nullable
|
||||
protected T[] data;
|
||||
|
||||
/**
|
||||
* The current selection or null.
|
||||
*/
|
||||
@Nullable
|
||||
protected Float selection;
|
||||
|
||||
@NonNull
|
||||
protected Paint bitmapBorderPaint = new Paint();
|
||||
|
||||
/**
|
||||
* The color for the background.
|
||||
*/
|
||||
private int colorNormal;
|
||||
|
||||
/**
|
||||
* The canvas to draw on the bitmap.
|
||||
*/
|
||||
private Canvas bitmapCanvas;
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public DataView(Context context) {
|
||||
super(context);
|
||||
init(context, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
*/
|
||||
public DataView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context, attrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The style attrs.
|
||||
*/
|
||||
public DataView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context, attrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The style attrs.
|
||||
* @param defStyleRes The style res.
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public DataView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context, attrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attribute set.
|
||||
*/
|
||||
private void init(Context context, @Nullable AttributeSet attrs) {
|
||||
colorNormal = ResourcesCompat.getColor(context.getResources(), R.color.normal, null);
|
||||
DisplayMetrics m = getResources().getDisplayMetrics();
|
||||
bitmapSize = (int)(m.density * 48 + 0.5);
|
||||
bitmapBorderPaint.setColor(ResourcesCompat.getColor(context.getResources(), R.color.inverse, null));
|
||||
bitmapBorderPaint.setStyle(Paint.Style.STROKE);
|
||||
bitmapBorderPaint.setStrokeWidth(4);
|
||||
if (attrs != null) {
|
||||
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DataView);
|
||||
int type = ta.getInt(R.styleable.DataView_direction,-1);
|
||||
if (type >= 0 && type < Direction.values().length) {
|
||||
this.direction = Direction.values()[type];
|
||||
}
|
||||
ta.recycle();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the drawing direction.
|
||||
*
|
||||
* @param direction The drawing direction.
|
||||
*/
|
||||
public void setDirection(@NonNull Direction direction) {
|
||||
this.direction = direction;
|
||||
updateBitmap();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the drawing direction.
|
||||
*
|
||||
* @return The drawing direction.
|
||||
*/
|
||||
@NonNull
|
||||
public Direction getDirection() {
|
||||
return direction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current data.
|
||||
*
|
||||
* @param data The data.
|
||||
*/
|
||||
public void setData(@Nullable T[] data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current data.
|
||||
*
|
||||
* @return The current data.
|
||||
*/
|
||||
@Nullable
|
||||
public T[] getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the data at the relative position.
|
||||
*
|
||||
* @param pos The relative position.
|
||||
* @return The data.
|
||||
*/
|
||||
@Nullable
|
||||
public T getDataAt(float pos) {
|
||||
if (data == null || data.length == 0) return null;
|
||||
int idx = (int)((data.length - 1) * pos);
|
||||
idx = Math.min(Math.max(0, idx), data.length - 1);
|
||||
return data[idx];
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
long now = System.currentTimeMillis();
|
||||
super.onDraw(canvas);
|
||||
onDrawData(now, canvas);
|
||||
if (selection != null) {
|
||||
bitmap.eraseColor(colorNormal);
|
||||
if (getBackground() != null) {
|
||||
getBackground().draw(bitmapCanvas);
|
||||
}
|
||||
bitmapCanvas.save();
|
||||
if (direction == Direction.VERTICAL) {
|
||||
bitmapCanvas.scale(1, 3);
|
||||
bitmapCanvas.translate(0, -selection * getHeight() + bitmapSize / 6f);
|
||||
} else {
|
||||
bitmapCanvas.scale(3, 1);
|
||||
bitmapCanvas.translate(-selection * getWidth() + bitmapSize / 6f, 0);
|
||||
}
|
||||
onDrawData(now, bitmapCanvas);
|
||||
bitmapCanvas.restore();
|
||||
if (direction == Direction.VERTICAL) {
|
||||
bitmapCanvas.drawLine(0, 1, bitmap.getWidth(), 1, bitmapBorderPaint);
|
||||
bitmapCanvas.drawLine(0, bitmap.getHeight() - 2, bitmap.getWidth(), bitmap.getHeight() - 2, bitmapBorderPaint);
|
||||
canvas.drawBitmap(bitmap, 0, selection * getHeight() - bitmapSize / 2, null);
|
||||
} else {
|
||||
bitmapCanvas.drawLine( 1, 0, 1, bitmap.getHeight(), bitmapBorderPaint);
|
||||
bitmapCanvas.drawLine(bitmap.getWidth() - 2, 0, bitmap.getWidth() - 2, bitmap.getHeight(), bitmapBorderPaint);
|
||||
canvas.drawBitmap(bitmap, selection * getWidth() - bitmapSize / 2, 0, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setSelection(@Nullable Float selection) {
|
||||
this.selection = selection;
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Float getSelection() {
|
||||
return selection;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
super.onSizeChanged(w, h, oldw, oldh);
|
||||
updateBitmap();
|
||||
}
|
||||
|
||||
protected abstract void onDrawData(long time, Canvas canvas);
|
||||
|
||||
/**
|
||||
* Recomputes the bitmap based on the size.
|
||||
*/
|
||||
private void updateBitmap() {
|
||||
if (bitmap != null) {
|
||||
bitmap.recycle();
|
||||
bitmap = null;
|
||||
bitmapCanvas = null;
|
||||
}
|
||||
if (direction == Direction.VERTICAL) {
|
||||
if (getWidth() > 0) {
|
||||
bitmap = Bitmap.createBitmap(getWidth(), bitmapSize, Bitmap.Config.ARGB_8888);
|
||||
bitmapCanvas = new Canvas(bitmap);
|
||||
}
|
||||
} else {
|
||||
if (getHeight() > 0) {
|
||||
bitmap = Bitmap.createBitmap(bitmapSize, getHeight(), Bitmap.Config.ARGB_8888);
|
||||
bitmapCanvas = new Canvas(bitmap);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package com.mowesta.android.app.view;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.content.res.AppCompatResources;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* A gradient view that shows rain drops. This is used for the
|
||||
* precipitation.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DropView extends GradientView {
|
||||
|
||||
/**
|
||||
* The threshold for rain.
|
||||
*/
|
||||
private static final double DROP_THRESHOLD = 0.1;
|
||||
|
||||
/**
|
||||
* The maximum number of water drops to simulate.
|
||||
*/
|
||||
private static final int MAXIMUM_DROPS = 45;
|
||||
|
||||
/**
|
||||
* The speed of the drops in dp.
|
||||
*/
|
||||
private static final int DROP_SPEED = 20;
|
||||
|
||||
/**
|
||||
* The random number generator for drops.
|
||||
*/
|
||||
private Random random = new Random();
|
||||
|
||||
/**
|
||||
* The drawable for a water drop.
|
||||
*/
|
||||
private Drawable drawable;
|
||||
|
||||
/**
|
||||
* The sum of all rain used to skew the random
|
||||
* number generator.
|
||||
*/
|
||||
private double sqrtSum;
|
||||
|
||||
/**
|
||||
* The square roots of the data.
|
||||
*/
|
||||
private double[] sqrts;
|
||||
|
||||
/**
|
||||
* The water drops.
|
||||
*/
|
||||
private WaterDrop[] drops = null;
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public DropView(Context context) {
|
||||
super(context);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
*/
|
||||
public DropView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The style.
|
||||
*/
|
||||
public DropView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The style.
|
||||
* @param defStyleRes The style res.
|
||||
*/
|
||||
public DropView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
private void init(Context context) {
|
||||
drawable = AppCompatResources.getDrawable(context, R.drawable.fg_water_drop);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setData(Double[] data) {
|
||||
super.setData(data);
|
||||
sqrtSum = 0;
|
||||
if (data != null) {
|
||||
sqrts = new double[data.length];
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
if (data[i] > DROP_THRESHOLD) {
|
||||
sqrts[i] = Math.sqrt(data[i]);
|
||||
sqrtSum += sqrts[i];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sqrts = null;
|
||||
}
|
||||
updateDrops();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirection(@NonNull Direction direction) {
|
||||
super.setDirection(direction);
|
||||
updateDrops();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
super.onSizeChanged(w, h, oldw, oldh);
|
||||
updateDrops();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the drops after the data or size has changed.
|
||||
*/
|
||||
private void updateDrops() {
|
||||
if (data != null && data.length > 0 && sqrtSum > 0) {
|
||||
int count = Math.min((int) sqrtSum + 5, MAXIMUM_DROPS);
|
||||
drops = new WaterDrop[count];
|
||||
float density = getResources().getDisplayMetrics().density;
|
||||
for (int i = 0; i < drops.length; i++) {
|
||||
drops[i] = new WaterDrop(density);
|
||||
}
|
||||
postInvalidateOnAnimation();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onDrawData(long time, Canvas canvas) {
|
||||
super.onDrawData(time, canvas);
|
||||
if (drops != null) {
|
||||
for (int i = 0; i < drops.length; i++) {
|
||||
drops[i].animate(time);
|
||||
drops[i].draw(canvas);
|
||||
}
|
||||
postInvalidateOnAnimation();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A class to emulate a single water drop.
|
||||
*/
|
||||
private class WaterDrop {
|
||||
|
||||
/**
|
||||
* The current time.
|
||||
*/
|
||||
private long time;
|
||||
/**
|
||||
* The left corner.
|
||||
*/
|
||||
private float x;
|
||||
/**
|
||||
* The top corner.
|
||||
*/
|
||||
private float y;
|
||||
/**
|
||||
* The remaining distance that this drop will
|
||||
* travel (in y direction) before it fades out.
|
||||
*/
|
||||
private float distance;
|
||||
/**
|
||||
* The speed at which the drop moves down in
|
||||
* pixels per second.
|
||||
*/
|
||||
private int speed;
|
||||
/**
|
||||
* The size of the current drop in pixels.
|
||||
*/
|
||||
private float size;
|
||||
/**
|
||||
* The alpha value used for drawing.
|
||||
*/
|
||||
private float alpha;
|
||||
/**
|
||||
* The screen density to compute random sizes
|
||||
* in dp.
|
||||
*/
|
||||
private float density;
|
||||
|
||||
/**
|
||||
* Creates a new drop.
|
||||
*
|
||||
* @param density The screen density.
|
||||
*/
|
||||
private WaterDrop(float density) {
|
||||
this.density = density;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a new random starting location for the water drop
|
||||
* as well as the size, movement speed (larger drops are faster)
|
||||
* and the distance to travel.
|
||||
*/
|
||||
private void reset() {
|
||||
int value = random.nextInt(5);
|
||||
size = this.density * (value + 3);
|
||||
float speedFactor = 0.5f + (value + 1) / 10f;
|
||||
speed = (int)(speedFactor * density * DROP_SPEED);
|
||||
float percent = random.nextFloat();
|
||||
double position = percent * sqrtSum;
|
||||
double current = 0;
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
if (data[i] > DROP_THRESHOLD) current += sqrts[i];
|
||||
if (current >= position) {
|
||||
int start = i;
|
||||
int end = i;
|
||||
for (int j = start - 1; j >= Math.max(0, i - 8); j--) {
|
||||
if (data[j] > data[i]) start = j;
|
||||
else break;
|
||||
}
|
||||
for (int j = end + i; j < Math.min(data.length, i + 8); j++) {
|
||||
if (data[j] > data[i]) end = j;
|
||||
else break;
|
||||
}
|
||||
|
||||
if (direction == Direction.VERTICAL) {
|
||||
float dh = getHeight() / (float)data.length;
|
||||
y = dh * (start - random.nextFloat());
|
||||
x = (getWidth() - size) * random.nextFloat();
|
||||
distance = dh * (end + random.nextFloat()) - y;
|
||||
} else {
|
||||
float dw = getWidth() / (float)data.length;
|
||||
y = getHeight() * random.nextFloat();
|
||||
x = dw * (i + random.nextFloat());
|
||||
distance = (getHeight() - y) * random.nextFloat();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
alpha = 0.5f;
|
||||
}
|
||||
|
||||
/**
|
||||
* Animates the drop for the current time.
|
||||
*
|
||||
* @param time The current time.
|
||||
*/
|
||||
public void animate(long time) {
|
||||
if (this.time == 0) {
|
||||
reset();
|
||||
} else {
|
||||
moveBy(time - this.time);
|
||||
if (alpha <= 0) {
|
||||
reset();
|
||||
}
|
||||
}
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the animation forward by a delta t in millis.
|
||||
*
|
||||
* @param delta The delta t in millis.
|
||||
*/
|
||||
private void moveBy(long delta) {
|
||||
int shift = (int)(size * (random.nextFloat() - .5f));
|
||||
float dx = delta / 1000f;
|
||||
float newy = y + dx * speed;
|
||||
x = x + dx * shift;
|
||||
distance -= newy - y;
|
||||
alpha = (float)Math.min(1, Math.max(0, 1 + distance / (size / 2)));
|
||||
y = newy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the drop in its current state.
|
||||
*
|
||||
* @param canvas The canvas to draw onto.
|
||||
*/
|
||||
public void draw(Canvas canvas) {
|
||||
int a = (int)Math.max(0, Math.min(255, alpha * 255));
|
||||
drawable.setAlpha(a);
|
||||
int ix = (int)x;
|
||||
int iy = (int)y;
|
||||
int s = (int)(size * alpha);
|
||||
drawable.setBounds(ix, iy, ix + s, iy + s);
|
||||
drawable.draw(canvas);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.mowesta.android.app.view;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.google.android.gms.common.SignInButton;
|
||||
import com.mowesta.android.app.view.color.IColorScheme;
|
||||
|
||||
/**
|
||||
* A gradient view that joins two data items to get a color.
|
||||
* This is required to join the cloud depth and coverage.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DualGradientView extends GradientView {
|
||||
|
||||
/**
|
||||
* The secondary data.
|
||||
*/
|
||||
@Nullable
|
||||
private Double[] secondaryData;
|
||||
|
||||
/**
|
||||
* The secondary color scheme.
|
||||
*/
|
||||
@Nullable
|
||||
private IColorScheme secondaryColorScheme;
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public DualGradientView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
*/
|
||||
public DualGradientView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The default attributes.
|
||||
*/
|
||||
public DualGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The default attributes.
|
||||
* @param defStyleRes The default res.
|
||||
*/
|
||||
public DualGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the secondary color scheme.
|
||||
*
|
||||
* @param secondaryColorScheme The secondary color scheme.
|
||||
*/
|
||||
public void setSecondaryColorScheme(@Nullable IColorScheme secondaryColorScheme) {
|
||||
this.secondaryColorScheme = secondaryColorScheme;
|
||||
updateColors();
|
||||
updateGradient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the secondary data.
|
||||
*
|
||||
* @param secondaryData The secondary data.
|
||||
*/
|
||||
public void setSecondaryData(@Nullable Double[] secondaryData) {
|
||||
this.secondaryData = secondaryData;
|
||||
updateColors();
|
||||
updateGradient();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateColors() {
|
||||
super.updateColors();
|
||||
if (colors != null && secondaryData != null && secondaryColorScheme != null && secondaryData.length == colors.length) {
|
||||
for (int i = 0; i < colors.length; i++) {
|
||||
int cover = colors[i];
|
||||
int other = secondaryColorScheme.getColor(secondaryData[i]);
|
||||
colors[i] = (cover & 0xFF000000) | (other & 0x00FFFFFF);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package com.mowesta.android.app.view;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.LinearGradient;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Shader;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.mowesta.android.app.view.color.IColorScheme;
|
||||
|
||||
/**
|
||||
* A view to display weather information as a gradient that is
|
||||
* drawn efficiently using the graphics card of the device.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class GradientView extends DataView<Double> {
|
||||
|
||||
/**
|
||||
* The color scheme.
|
||||
*/
|
||||
@Nullable
|
||||
protected IColorScheme colorScheme;
|
||||
|
||||
/**
|
||||
* The colors for the data.
|
||||
*/
|
||||
@Nullable
|
||||
protected int[] colors;
|
||||
|
||||
/**
|
||||
* The positions for the data.
|
||||
*/
|
||||
@Nullable
|
||||
protected float[] positions;
|
||||
|
||||
/**
|
||||
* The gradient for the data.
|
||||
*/
|
||||
@Nullable
|
||||
protected LinearGradient gradient;
|
||||
|
||||
/**
|
||||
* The paint to draw the gradient.
|
||||
*/
|
||||
protected Paint paint = new Paint();
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public GradientView(Context context) {
|
||||
super(context);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attrs.
|
||||
*/
|
||||
public GradientView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attrs.
|
||||
* @param defStyleAttr The default style.
|
||||
*/
|
||||
public GradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attrs.
|
||||
* @param defStyleAttr The default style.
|
||||
* @param defStyleRes The default res.
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public GradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
private void init(Context context) {
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setData(Double[] data) {
|
||||
this.data = data;
|
||||
updatePositions();
|
||||
updateColors();
|
||||
updateGradient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the color scheme to render the data.
|
||||
*
|
||||
* @return The color scheme.
|
||||
*/
|
||||
@Nullable
|
||||
public IColorScheme getColorScheme() {
|
||||
return colorScheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the color scheme to render the data.
|
||||
*
|
||||
* @param colorScheme The color scheme.
|
||||
*/
|
||||
public void setColorScheme(@Nullable IColorScheme colorScheme) {
|
||||
this.colorScheme = colorScheme;
|
||||
updateColors();
|
||||
updateGradient();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirection(@NonNull Direction direction) {
|
||||
this.direction = direction;
|
||||
updateGradient();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDrawData(long time, Canvas canvas) {
|
||||
if (gradient != null) {
|
||||
paint.setShader(gradient);
|
||||
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
super.onSizeChanged(w, h, oldw, oldh);
|
||||
updateGradient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the gradient to draw the data.
|
||||
*/
|
||||
protected void updateGradient() {
|
||||
if (colors == null || positions == null) {
|
||||
gradient = null;
|
||||
} else {
|
||||
float x = direction == Direction.HORIZONTAL ? getWidth(): 0;
|
||||
float y = direction == Direction.HORIZONTAL ? 0 : getHeight();
|
||||
gradient = new LinearGradient(0, 0, x, y, colors, positions, Shader.TileMode.CLAMP);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the positions of the gradient.
|
||||
*/
|
||||
protected void updatePositions() {
|
||||
if (data == null) {
|
||||
positions = null;
|
||||
} else {
|
||||
positions = new float[data.length];
|
||||
for (int i = 0; i < positions.length; i++) {
|
||||
positions[i] = 0.5f/data.length + i/(float)data.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the colors of the gradient.
|
||||
*/
|
||||
protected void updateColors() {
|
||||
if (data == null || colorScheme == null) {
|
||||
colors = null;
|
||||
} else {
|
||||
colors = new int[data.length];
|
||||
for (int i = 0; i < colors.length; i++) {
|
||||
colors[i] = colorScheme.getColor(data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.mowesta.android.app.view;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.LinearGradient;
|
||||
import android.graphics.Matrix;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.Shader;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import com.locoslab.library.geometry.util.clipper.Clipper;
|
||||
import com.mowesta.android.app.R;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* This data view generates particles moving at a data-dependent
|
||||
* speed. The particles are drawn as a linear gradient. The size
|
||||
* of the gradient also depends on the speed. This view is used
|
||||
* to draw the wind speed.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ParticleView extends DataView<Double> {
|
||||
|
||||
/**
|
||||
* A random number generator to share across all
|
||||
* particles.
|
||||
*/
|
||||
@NonNull
|
||||
private Random random = new Random();
|
||||
|
||||
/**
|
||||
* The particles that store their current position.
|
||||
*/
|
||||
@Nullable
|
||||
private Particle[] particles;
|
||||
|
||||
/**
|
||||
* The paint to draw the particles.
|
||||
*/
|
||||
@NonNull
|
||||
private Paint paint = new Paint();
|
||||
|
||||
/**
|
||||
* A factor to speed up or slow down the motion. This
|
||||
* factor is multiplied by the speed in meter per second
|
||||
* to get the motion in pixels per second.
|
||||
*/
|
||||
private float speedFactor = 10;
|
||||
|
||||
/**
|
||||
* The relative length of the particle tails. This
|
||||
* is used to derive the maximum length.
|
||||
*/
|
||||
private float relativeLength = .5f;
|
||||
|
||||
/**
|
||||
* The relative height of the particle tails. This
|
||||
* is used to derive the stroke width.
|
||||
*/
|
||||
private float relativeHeight = .5f;
|
||||
|
||||
/**
|
||||
* The randomized start time.
|
||||
*/
|
||||
private int randomizeTime = 2000;
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public ParticleView(Context context) {
|
||||
super(context);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attrs.
|
||||
*/
|
||||
public ParticleView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attrs.
|
||||
* @param defStyleAttr The default style attrs.
|
||||
*/
|
||||
public ParticleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attrs.
|
||||
* @param defStyleAttr The default style attrs.
|
||||
* @param defStyleRes The default style res.
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public ParticleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
private void init(Context context) {
|
||||
paint.setStyle(Paint.Style.STROKE);
|
||||
paint.setStrokeCap(Paint.Cap.ROUND);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void onDrawData(long time, Canvas canvas) {
|
||||
if (particles != null) {
|
||||
for (int i = particles.length - 1; i >= 0; i--) {
|
||||
particles[i].animate(time);
|
||||
particles[i].draw(canvas, paint);
|
||||
}
|
||||
postInvalidateOnAnimation();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setData(@Nullable Double[] data) {
|
||||
super.setData(data);
|
||||
updateParticles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirection(@NonNull Direction direction) {
|
||||
super.setDirection(direction);
|
||||
updateParticles();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
super.onSizeChanged(w, h, oldw, oldh);
|
||||
updateParticles();
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-computes the particle's based on the data and the direction.
|
||||
*/
|
||||
private void updateParticles() {
|
||||
int width = getWidth();
|
||||
int height = getHeight();
|
||||
if (data == null || data.length == 0 || width == 0 || height == 0) {
|
||||
particles = null;
|
||||
} else {
|
||||
Direction dir = direction==Direction.VERTICAL?Direction.HORIZONTAL:Direction.VERTICAL;
|
||||
int color = ResourcesCompat.getColor(getResources(), R.color.particle, null);
|
||||
double max = 0;
|
||||
for (int i = 0; i < data.length; i++)
|
||||
max = Math.max(max, data[i]);
|
||||
particles = new Particle[data.length];
|
||||
float cell = (direction == Direction.VERTICAL?height:width) / (float)data.length;
|
||||
float length = (direction == Direction.VERTICAL?width:height) * relativeLength;
|
||||
float size = direction == Direction.VERTICAL?width:height;
|
||||
paint.setStrokeWidth(cell * relativeHeight);
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
RectF rect = direction == Direction.VERTICAL ? new RectF(0, cell * i, size, cell * (i + 1)) :
|
||||
new RectF(cell * i, 0, cell * (i + 1), size);
|
||||
float speed = (float)(speedFactor * data[i]);
|
||||
float tail = (float)(max == 0 ? 0 : (data[i] / max)) * length;
|
||||
particles[i] = new Particle(random, rect, dir, color, speed, tail, randomizeTime);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A single particle that moves into horizontal or vertical direction.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private static class Particle {
|
||||
|
||||
/** A random number generator to make the particle less predictable. */
|
||||
@NonNull
|
||||
private Random random;
|
||||
|
||||
/** The movement direction (horizontal: left to right, vertical: top to bottom). */
|
||||
@NonNull
|
||||
private Direction direction;
|
||||
|
||||
/** The rectangle in which we draw. */
|
||||
@NonNull
|
||||
private RectF rect;
|
||||
|
||||
/** The current x-position of the particle (head). */
|
||||
private float x;
|
||||
/** The current y-position of the particle (head). */
|
||||
private float y;
|
||||
/** The length of the particle's tail. */
|
||||
private float length;
|
||||
/** The movement speed in pixels per second. */
|
||||
private float speed;
|
||||
/** The time used to randomize restarts. */
|
||||
private int randomize;
|
||||
/** The time when the particle's position was last computed. */
|
||||
private long time;
|
||||
|
||||
/** A gradient to quickly draw the particle. */
|
||||
@NonNull
|
||||
private LinearGradient gradient;
|
||||
/** The translation matrix to avoid object allocations. */
|
||||
@NonNull
|
||||
private Matrix matrix = new Matrix();
|
||||
|
||||
/**
|
||||
* A single particle that moves either vertically or horizontally.
|
||||
*
|
||||
* @param random A random number generator.
|
||||
* @param rect The rectangle in which the particle moves.
|
||||
* @param direction The direction to move (left to right or top to bottom).
|
||||
* @param speed The movement speed in pixels per second.
|
||||
* @param length The length of the tail of the particle.
|
||||
* @param randomize The time used to randomize the restart when the particle moved off the screen.
|
||||
*/
|
||||
public Particle(@NonNull Random random, @NonNull RectF rect, @NonNull Direction direction, int color, float speed, float length, int randomize) {
|
||||
this.random = random;
|
||||
this.direction = direction;
|
||||
this.rect = rect;
|
||||
this.speed = speed;
|
||||
this.length = length;
|
||||
this.randomize = randomize;
|
||||
gradient = new LinearGradient(0, 0,
|
||||
direction == Direction.HORIZONTAL?length:0,
|
||||
direction == Direction.HORIZONTAL?0:length,
|
||||
new int[] { 0x00ffffff, color },
|
||||
new float[] { 0f, 1f}, Shader.TileMode.CLAMP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the particle onto the canvas.
|
||||
*
|
||||
* @param c The canvas.
|
||||
* @param paint The paint to draw with.
|
||||
*/
|
||||
public void draw(Canvas c, Paint paint) {
|
||||
float xs = (direction == Direction.HORIZONTAL)? x - length: x;
|
||||
float ys = (direction == Direction.HORIZONTAL)? y : y - length;
|
||||
matrix.setTranslate(xs, ys);
|
||||
gradient.setLocalMatrix(matrix);
|
||||
paint.setShader(gradient);
|
||||
c.drawLine(xs , ys, x, y, paint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the animation state based on the time.
|
||||
*
|
||||
* @param time The time.
|
||||
*/
|
||||
public void animate(long time) {
|
||||
if (this.time == 0 || isFinished()) {
|
||||
reset(this.time == 0);
|
||||
} else {
|
||||
moveBy(time - this.time);
|
||||
}
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the particle has moved out of sight.
|
||||
*
|
||||
* @return True if it has moved out of sight. False otherwise.
|
||||
*/
|
||||
private boolean isFinished() {
|
||||
if (direction == Direction.HORIZONTAL) {
|
||||
return x - length > rect.right;
|
||||
} else {
|
||||
return y - length > rect.bottom;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the particle to a new initial position.
|
||||
*
|
||||
* @param init True, if the positions shall be randomly distributed.
|
||||
*/
|
||||
private void reset(boolean init) {
|
||||
float movement = random.nextInt(randomize) / 1000f * speed;
|
||||
if (direction == Direction.HORIZONTAL) {
|
||||
x = rect.left - movement + (init?rect.width() * random.nextFloat():0);
|
||||
y = rect.top + (rect.bottom - rect.top) * 0.5f;
|
||||
} else {
|
||||
x = rect.left + (rect.right - rect.left) * 0.5f;
|
||||
y = rect.top - movement + (init?rect.height() * random.nextFloat():0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the particle depending on the time passed.
|
||||
*
|
||||
* @param delta The time passed in milliseconds.
|
||||
*/
|
||||
private void moveBy(long delta) {
|
||||
float movement = delta / 1000f * speed;
|
||||
if (direction == Direction.HORIZONTAL) {
|
||||
x += movement;
|
||||
} else {
|
||||
y += movement;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package com.mowesta.android.app.view;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.content.res.AppCompatResources;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.util.TimeUtils;
|
||||
|
||||
/**
|
||||
* The view to display the time and to handle touch events.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class TimeView extends DataView<Long> {
|
||||
|
||||
/**
|
||||
* An interface for listeners that want to be
|
||||
* informed about touch events.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface OnSlideListener {
|
||||
|
||||
/**
|
||||
* Called when there is a slide event on the view at
|
||||
* the specified relative position.
|
||||
*
|
||||
* @param relative The relative position (0 to 1).
|
||||
*/
|
||||
void onSlide(float relative);
|
||||
|
||||
|
||||
void onSlideEnd();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A listener to handle the touch events on the view.
|
||||
*
|
||||
*/
|
||||
private static class TouchListener implements View.OnTouchListener {
|
||||
|
||||
/** The epsilon to ignore duplicate events. */
|
||||
private float EPSILON = 0.0001f;
|
||||
|
||||
/** The time view that is observed by this listener. */
|
||||
private TimeView view;
|
||||
|
||||
/** A cache for the view position.*/
|
||||
private int[] viewPosition = new int[2];
|
||||
|
||||
/**
|
||||
* If down, the id of the pointer that we are tracking.
|
||||
*/
|
||||
private int id = 0;
|
||||
|
||||
/**
|
||||
* A boolean to memorize whether we already saw a finger going down.
|
||||
*/
|
||||
private boolean down = false;
|
||||
|
||||
/**
|
||||
* The last relative position that we saw.
|
||||
*/
|
||||
private float position = 0;
|
||||
|
||||
@NonNull
|
||||
private OnSlideListener listener;
|
||||
|
||||
public TouchListener(@NonNull TimeView view, @NonNull OnSlideListener listener) {
|
||||
this.view = view;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouch(View v, MotionEvent event) {
|
||||
updateViewPosition();
|
||||
int index = event.getActionIndex();
|
||||
int mask = event.getActionMasked();
|
||||
boolean onView = isOnView(event);
|
||||
switch (mask) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
if (! down && onView) {
|
||||
down = true;
|
||||
id = event.getPointerId(index);
|
||||
position = getPosition(event);
|
||||
listener.onSlide(position);
|
||||
};
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (down && id == event.getPointerId(index)) {
|
||||
float np = getPosition(event);
|
||||
if (Math.abs(np - position) > EPSILON) {
|
||||
position = np;
|
||||
listener.onSlide(position);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
case MotionEvent.ACTION_UP:
|
||||
if (down && id == event.getPointerId(index)) {
|
||||
down = false;
|
||||
listener.onSlideEnd();
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return down;
|
||||
}
|
||||
|
||||
private void updateViewPosition() {
|
||||
view.getLocationOnScreen(viewPosition);
|
||||
}
|
||||
|
||||
private float getPosition(MotionEvent event) {
|
||||
if (view.getDirection() == Direction.HORIZONTAL) {
|
||||
if (view.getWidth() == 0) return 0;
|
||||
float x = event.getRawX();
|
||||
return Math.min(1, Math.max(0, (x - viewPosition[0]) / view.getWidth()));
|
||||
} else {
|
||||
if (view.getHeight() == 0) return 0;
|
||||
float y = event.getRawY();
|
||||
return Math.min(1, Math.max(0, (y - viewPosition[1]) / view.getHeight()));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isOnView(MotionEvent event) {
|
||||
float x = event.getRawX();
|
||||
float y = event.getRawY();
|
||||
return x >= viewPosition[0] && x < viewPosition[0] + view.getWidth()
|
||||
&& y >= viewPosition[1] && y < viewPosition[1] + view.getHeight();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The timezone.
|
||||
*/
|
||||
private String timezone;
|
||||
|
||||
/**
|
||||
* The positions to draw lines.
|
||||
*/
|
||||
private float[] positions;
|
||||
|
||||
/**
|
||||
* The lengths of the lines at the positions.
|
||||
*/
|
||||
private float[] lengths;
|
||||
|
||||
/**
|
||||
* The paint to draw the lines.
|
||||
*/
|
||||
private Paint paint = new Paint();
|
||||
|
||||
/**
|
||||
* The paint to draw the current time.
|
||||
*/
|
||||
private Paint paintNow = new Paint();
|
||||
|
||||
/**
|
||||
* The circle animation.
|
||||
*/
|
||||
private TouchCircleAnimation animation = new TouchCircleAnimation(this);
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public TimeView(Context context) {
|
||||
super(context);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
*/
|
||||
public TimeView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The default attributes.
|
||||
*/
|
||||
public TimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new view.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param attrs The attributes.
|
||||
* @param defStyleAttr The default attributes.
|
||||
* @param defStyleRes The default style.
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public TimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
init(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the view.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
private void init(Context context) {
|
||||
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
|
||||
paint.setStrokeWidth((int)(1f * displayMetrics.density + .5f));
|
||||
paint.setColor(ResourcesCompat.getColor(context.getResources(), R.color.inverse, null));
|
||||
paint.setAntiAlias(true);
|
||||
paintNow.setStrokeWidth((int)(2f * displayMetrics.density + .5f));
|
||||
paintNow.setColor(ResourcesCompat.getColor(context.getResources(), R.color.primary, null));
|
||||
paintNow.setAntiAlias(true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates an touch listener for this view.
|
||||
*
|
||||
* @param listener The listener to keep track of events.
|
||||
* @return The touch listener.
|
||||
*/
|
||||
public View.OnTouchListener createOnTouchListener(@NonNull OnSlideListener listener) {
|
||||
return new TouchListener(this, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the timezone to draw the hours.
|
||||
*
|
||||
* @param timezone The timezone.
|
||||
*/
|
||||
public void setTimezone(String timezone) {
|
||||
this.timezone = timezone;
|
||||
updateTimes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time zone.
|
||||
*
|
||||
* @return The timezone.
|
||||
*/
|
||||
public String getTimezone() {
|
||||
return timezone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setData(@Nullable Long[] data) {
|
||||
super.setData(data);
|
||||
updateTimes();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
super.onSizeChanged(w, h, oldw, oldh);
|
||||
updateTimes();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDrawData(long time, Canvas canvas) {
|
||||
animation.animate(time);
|
||||
animation.draw(canvas);
|
||||
if (positions != null) {
|
||||
// draw now
|
||||
for (int i = 1; i < data.length; i++) {
|
||||
if (time > data[i - 1] && time <= data[i]) {
|
||||
float fraction = (data[i] - time) / (data[i] - data[i - 1]);
|
||||
float pos = (direction == Direction.VERTICAL?getHeight():getWidth()) * (i + fraction) / data.length;
|
||||
float end = direction == Direction.VERTICAL?getWidth():getHeight();
|
||||
if (direction == Direction.VERTICAL) {
|
||||
canvas.drawLine(0, pos, end, pos, paintNow);
|
||||
} else {
|
||||
canvas.drawLine(pos, 0, pos, end, paintNow);
|
||||
}
|
||||
}
|
||||
}
|
||||
// draw grid
|
||||
float center = (direction == Direction.VERTICAL?getWidth():getHeight()) / 2f;
|
||||
for (int i = 0; i < positions.length; i++) {
|
||||
float xs = direction == Direction.VERTICAL?center - .5f * lengths[i]:positions[i];
|
||||
float xe = direction == Direction.VERTICAL?center + .5f * lengths[i]:positions[i];
|
||||
float ys = direction == Direction.HORIZONTAL?center - .5f * lengths[i]:positions[i];
|
||||
float ye = direction == Direction.HORIZONTAL?center + .5f * lengths[i]:positions[i];
|
||||
canvas.drawLine(xs, ys, xe, ye, paint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateTimes() {
|
||||
if (data == null || data.length == 0) {
|
||||
lengths = null;
|
||||
positions = null;
|
||||
} else {
|
||||
int[] hours = new int[data.length];
|
||||
TimeUtils time = new TimeUtils(System.currentTimeMillis(), timezone);
|
||||
int ranges = 0;
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
hours[i] = time.getHour(data[i]);
|
||||
if (hours[i] % 6 == 0) {
|
||||
ranges += 1;
|
||||
}
|
||||
}
|
||||
positions = new float[ranges];
|
||||
lengths = new float[ranges];
|
||||
int index = 0;
|
||||
int total = direction == Direction.VERTICAL?getHeight():getWidth();
|
||||
int max = direction == Direction.VERTICAL?getWidth():getHeight();
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
if (hours[i] % 6 == 0) {
|
||||
positions[index] = ((float)total / data.length) * (i + .5f);
|
||||
lengths[index] = hours[i] == 0 ? (max * .75f): (max * 0.25f);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private class TouchCircleAnimation {
|
||||
|
||||
/** The center of the click. */
|
||||
float cx, cy;
|
||||
/** The animated radius. */
|
||||
float radius;
|
||||
/** The animated alpha value. */
|
||||
float alpha;
|
||||
/** The speed at which the circle expands. */
|
||||
float expand = 500;
|
||||
/**
|
||||
* The speed at which the alpha value decays.
|
||||
*/
|
||||
float fade = 2f;
|
||||
/** The Animation time. */
|
||||
long time = 0;
|
||||
/** The number of repeatitions. */
|
||||
int repeat = 0;
|
||||
/** A boolean to indicate when done. */
|
||||
boolean done = false;
|
||||
/** The paint to draw. */
|
||||
Paint paint = new Paint();
|
||||
/** The view. */
|
||||
DataView<?> view;
|
||||
/** The finger drawable. */
|
||||
Drawable touch;
|
||||
|
||||
public TouchCircleAnimation(DataView<?> view) {
|
||||
this.view = view;
|
||||
this.touch = AppCompatResources.getDrawable(view.getContext(), R.drawable.ic_touch_app_normal_24);
|
||||
paint.setColor(ResourcesCompat.getColor(view.getResources(), R.color.accent, null));
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
}
|
||||
|
||||
|
||||
public void animate(long now) {
|
||||
if (time == 0) {
|
||||
reset();
|
||||
} else {
|
||||
updateBy(now - time);
|
||||
if (alpha < 0) {
|
||||
reset();
|
||||
}
|
||||
}
|
||||
time = now;
|
||||
done = repeat > 3;
|
||||
}
|
||||
|
||||
private void updateBy(long delta) {
|
||||
float dx = delta / 1000f;
|
||||
alpha -= dx * fade;
|
||||
radius += dx * expand;
|
||||
}
|
||||
|
||||
|
||||
public void draw(Canvas c) {
|
||||
if (!done) {
|
||||
if (repeat > 1) {
|
||||
int a = (int)Math.min(255, Math.max(0, 255 * alpha));
|
||||
paint.setAlpha(Math.min(255, a + 128));
|
||||
c.drawCircle(cx, cy, radius, paint);
|
||||
touch.setAlpha(a);
|
||||
touch.draw(c);
|
||||
}
|
||||
postInvalidateOnAnimation();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void reset() {
|
||||
cx = getWidth() / 2;
|
||||
cy = getHeight() / 2;
|
||||
if (view.direction == Direction.VERTICAL) {
|
||||
cy = cy / 2f;
|
||||
}
|
||||
int padding = (int)(Math.min(getWidth(), getHeight()) * 0.1f);
|
||||
int size = Math.min(getWidth(), getHeight()) / 2 - padding;
|
||||
touch.setBounds((int)cx - size, (int)cy - size, (int)cx + size, (int) cy + size);
|
||||
radius = 1;
|
||||
alpha = 1;
|
||||
repeat += 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.LinearInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A color scheme for the cloud depth.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CloudDepthColorScheme extends InterpolatedColorScheme {
|
||||
|
||||
/**
|
||||
* The list of supports.
|
||||
*/
|
||||
private static List<ColorSupport> SUPPORT = new ArrayList<>();
|
||||
|
||||
static {
|
||||
SUPPORT.add(new ColorSupport(0, 0x00FFFFFF));
|
||||
SUPPORT.add(new ColorSupport(1, 0xFF999999));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new color scheme to render the cloud depth.
|
||||
*/
|
||||
public CloudDepthColorScheme() {
|
||||
super(SUPPORT, new LinearInterpolation());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.LinearInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The color scheme for relative humidity.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class HumidityColorScheme extends InterpolatedColorScheme {
|
||||
|
||||
/**
|
||||
* The support vector with the temperature to color mapping.
|
||||
*/
|
||||
private static List<ColorSupport> SUPPORT = new ArrayList<>();
|
||||
|
||||
static {
|
||||
SUPPORT.add(new ColorSupport(0, 0x0042BAD0));
|
||||
SUPPORT.add(new ColorSupport(100, 0xFF42BAD0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a color scheme.
|
||||
*/
|
||||
public HumidityColorScheme() {
|
||||
super(SUPPORT, new LinearInterpolation());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
/**
|
||||
* A color scheme is responsible for mapping a data
|
||||
* value to an ARGB color.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface IColorScheme {
|
||||
|
||||
/**
|
||||
* Returns the color for the data value.
|
||||
*
|
||||
* @param value The data value.
|
||||
* @return The ARGB value with 8 bit resolution.
|
||||
*/
|
||||
int getColor(double value);
|
||||
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.IDataInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A color scheme for temperature given in degrees Kelvin.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class InterpolatedColorScheme implements IColorScheme {
|
||||
|
||||
/**
|
||||
* A support point that defines the color for a particular value.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class ColorSupport implements Comparable<ColorSupport> {
|
||||
|
||||
/**
|
||||
* The value.
|
||||
*/
|
||||
protected double value;
|
||||
/**
|
||||
* The red component.
|
||||
*/
|
||||
protected int red;
|
||||
/**
|
||||
* The green component (0 - 255).
|
||||
*/
|
||||
protected int green;
|
||||
/**
|
||||
* The blue component.
|
||||
*/
|
||||
protected int blue;
|
||||
/**
|
||||
* The alpha component.
|
||||
*/
|
||||
protected int alpha;
|
||||
|
||||
/**
|
||||
* Creates the support for the specified color.
|
||||
*
|
||||
* @param value The value that should exhibit the color.
|
||||
* @param argb The color value.
|
||||
*/
|
||||
public ColorSupport(double value, int argb) {
|
||||
this(value, (argb >> 24) & 0xff, (argb >> 16) & 0xff, (argb >> 8) & 0xff, argb & 0xff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new support at a particular value.
|
||||
*
|
||||
* @param value The data value that should exhibit the color.
|
||||
* @param a The alpha value.
|
||||
* @param r The red value.
|
||||
* @param g The green value.
|
||||
* @param b The blue value.
|
||||
*/
|
||||
public ColorSupport(double value, int a, int r, int g, int b) {
|
||||
this.value = value;
|
||||
this.alpha = a & 0xff;
|
||||
this.red = r & 0xff;
|
||||
this.green = g & 0xff;
|
||||
this.blue = b & 0xff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value.
|
||||
*
|
||||
* @return The value.
|
||||
*/
|
||||
public double getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the color as ARGB int.
|
||||
*
|
||||
* @return The color as ARGB int.
|
||||
*/
|
||||
public int getColor() {
|
||||
return alpha << 24 | red << 16 | green << 8 | blue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the blue component (0-255).
|
||||
*
|
||||
* @return The blue component.
|
||||
*/
|
||||
public int getRed() {
|
||||
return red;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the blue component (0-255).
|
||||
*
|
||||
* @return The blue component.
|
||||
*/
|
||||
public int getGreen() {
|
||||
return green;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the blue component (0-255).
|
||||
*
|
||||
* @return The blue component.
|
||||
*/
|
||||
public int getAlpha() {
|
||||
return alpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the blue component (0-255).
|
||||
*
|
||||
* @return The blue component.
|
||||
*/
|
||||
public int getBlue() {
|
||||
return blue;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int compareTo(ColorSupport o) {
|
||||
return Double.compare(value, o.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The supporting points.
|
||||
*/
|
||||
protected List<ColorSupport> supports;
|
||||
/**
|
||||
* The interpolation strategy.
|
||||
*/
|
||||
protected IDataInterpolation interpolation;
|
||||
|
||||
/**
|
||||
* Creates an interpolated color scheme.
|
||||
*
|
||||
* @param supports The supports.
|
||||
* @param interpolation The interpolation strategy.
|
||||
*/
|
||||
public InterpolatedColorScheme(List<ColorSupport> supports, IDataInterpolation interpolation) {
|
||||
if (supports.isEmpty()) throw new IllegalArgumentException("At least one color support point must be specified.");
|
||||
this.supports = new ArrayList<>(supports);
|
||||
this.interpolation = interpolation;
|
||||
Collections.sort(supports);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getColor(double data) {
|
||||
// data is smaller than any support, return lowest support color
|
||||
if (data < supports.get(0).getValue()) return supports.get(0).getColor();
|
||||
for (int i = 1; i < supports.size(); i++) {
|
||||
if (supports.get(i).getValue() > data) {
|
||||
return getColor(supports.get(i - 1), supports.get(i), data);
|
||||
}
|
||||
}
|
||||
// data is larger than any support, return highest support color
|
||||
return supports.get(supports.size() - 1).getColor();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the interpolated color for the value.
|
||||
*
|
||||
* @param from The lower support.
|
||||
* @param to The higher support.
|
||||
* @param value The data value.
|
||||
* @return The interpolated color.
|
||||
*/
|
||||
private int getColor(ColorSupport from, ColorSupport to, double value) {
|
||||
double fraction = (value - from.getValue()) / (double)(to.getValue() - from.getValue());
|
||||
int alpha = getColor(from.getAlpha(), to.getAlpha(), fraction);
|
||||
int red = getColor(from.getRed(), to.getRed(), fraction);
|
||||
int green = getColor(from.getGreen(), to.getGreen(), fraction);
|
||||
int blue = getColor(from.getBlue(), to.getBlue(), fraction);
|
||||
return alpha << 24 | red << 16 | green << 8 | blue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the interpolated color value and ensures that it
|
||||
* lies within the target bounds.
|
||||
*
|
||||
* @param from The start color value.
|
||||
* @param to The to color value.
|
||||
* @param fraction The fraction between from and to.
|
||||
* @return The color value.
|
||||
*/
|
||||
private int getColor(int from, int to, double fraction) {
|
||||
double r = interpolation.interpolate(from, to, fraction);
|
||||
return Math.min(255, Math.max(0, (int)Math.round(r)));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.LinearInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The color scheme for precipitation (rain, snow, etc.).
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class PrecipitationColorScheme extends InterpolatedColorScheme {
|
||||
|
||||
/**
|
||||
* The support vector with the temperature to color mapping.
|
||||
*/
|
||||
private static List<ColorSupport> SUPPORT = new ArrayList<>();
|
||||
|
||||
static {
|
||||
SUPPORT.add(new ColorSupport(0, 0x0000000));
|
||||
SUPPORT.add(new ColorSupport(0.1, 0x88008800));
|
||||
SUPPORT.add(new ColorSupport(1, 0xFF00FF00)); // Nieselregen (<1)
|
||||
SUPPORT.add(new ColorSupport(10, 0xFF00FFFF));
|
||||
SUPPORT.add(new ColorSupport(20, 0xFF0000FF)); // Starkregen (>20)
|
||||
SUPPORT.add(new ColorSupport(20, 0xFF880000));
|
||||
SUPPORT.add(new ColorSupport(35, 0xFFFF0000)); // Unwetter (>35)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a color scheme.
|
||||
*/
|
||||
public PrecipitationColorScheme() {
|
||||
super(SUPPORT, new LinearInterpolation());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.LinearInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A color scheme that makes low pressure zones blue and high
|
||||
* pressure zones red.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class PressureColorScheme extends InterpolatedColorScheme {
|
||||
|
||||
/**
|
||||
* Creates a pressure color scheme.
|
||||
*
|
||||
* @param avg The average value.
|
||||
* @param min The minimum value.
|
||||
* @param max The maximum value.
|
||||
*/
|
||||
public PressureColorScheme(double avg, double min, double max) {
|
||||
super(createSupport(avg, min, max), new LinearInterpolation());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the support for the color scheme based on the average,
|
||||
* minimum and maximum values.
|
||||
*
|
||||
* @param avg The average.
|
||||
* @param min The minimum.
|
||||
* @param max The maximum.
|
||||
* @return The support for the scheme.
|
||||
*/
|
||||
private static List<ColorSupport> createSupport(double avg, double min, double max) {
|
||||
List<ColorSupport> result = new ArrayList<>();
|
||||
result.add(new ColorSupport(min, 255, 0, 0, 0));
|
||||
result.add(new ColorSupport(avg, 255, 0, 0, 255));
|
||||
result.add(new ColorSupport(max, 255, 255, 0, 255));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.IDataInterpolation;
|
||||
import com.mowesta.android.app.view.interpolation.LinearInterpolation;
|
||||
import com.mowesta.android.app.view.interpolation.StepInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A color scheme that is extracted from the climate charts of DWD.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ScientificTemperatureColorScheme extends InterpolatedColorScheme {
|
||||
|
||||
/**
|
||||
* The support vector with the temperature to color mapping.
|
||||
*/
|
||||
private static List<ColorSupport> SUPPORT = new ArrayList<>();
|
||||
|
||||
static {
|
||||
SUPPORT.add(new ColorSupport(-35, 0xFF0000FB));
|
||||
SUPPORT.add(new ColorSupport(-30, 0xFF2E46FF));
|
||||
SUPPORT.add(new ColorSupport(-25, 0xFF3974FF));
|
||||
SUPPORT.add(new ColorSupport(-20, 0xFF39A9FF));
|
||||
SUPPORT.add(new ColorSupport(-15, 0xFF29DBFF));
|
||||
SUPPORT.add(new ColorSupport(-10, 0xFF30FFEF));
|
||||
SUPPORT.add(new ColorSupport(-5, 0xFF88FFBE));
|
||||
SUPPORT.add(new ColorSupport(0, 0xFFB6FE8E));
|
||||
SUPPORT.add(new ColorSupport(0, 0xFFFFFF00));
|
||||
SUPPORT.add(new ColorSupport(5, 0xFFDAFF61));
|
||||
SUPPORT.add(new ColorSupport(10, 0xFFF8FF26));
|
||||
SUPPORT.add(new ColorSupport(15, 0xFFFEE100));
|
||||
SUPPORT.add(new ColorSupport(20, 0xFFFFB200));
|
||||
SUPPORT.add(new ColorSupport(25, 0xFFFE8500));
|
||||
SUPPORT.add(new ColorSupport(30, 0xFFFF5100));
|
||||
SUPPORT.add(new ColorSupport(35, 0xFFB30000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a color scheme with linear interpolation.
|
||||
*/
|
||||
public ScientificTemperatureColorScheme() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a color scheme with linear or step-wise interpolation.
|
||||
*
|
||||
* @param linearInterpolation If set to true, enables linear interpolation.
|
||||
*/
|
||||
public ScientificTemperatureColorScheme(boolean linearInterpolation) {
|
||||
super(SUPPORT, linearInterpolation?new LinearInterpolation():new StepInterpolation(1f));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a colors scheme with the specified interpolation.
|
||||
*
|
||||
* @param interpolation The interpolation function.
|
||||
*/
|
||||
public ScientificTemperatureColorScheme(IDataInterpolation interpolation) {
|
||||
super(SUPPORT, interpolation);
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.mowesta.android.app.view.color;
|
||||
|
||||
import com.mowesta.android.app.view.interpolation.LinearInterpolation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A color scheme for the cloud coverage provided as a value between 0 and 1.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class WhiteCloudColorScheme extends InterpolatedColorScheme {
|
||||
|
||||
/**
|
||||
* The support vector with the temperature to color mapping.
|
||||
*/
|
||||
private static List<ColorSupport> SUPPORT = new ArrayList<>();
|
||||
|
||||
static {
|
||||
SUPPORT.add(new ColorSupport(0, 0x00FFFFFF));
|
||||
SUPPORT.add(new ColorSupport(1, 0xFFFFFFFF));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a color scheme with linear interpolation.
|
||||
*/
|
||||
public WhiteCloudColorScheme() {
|
||||
super(SUPPORT, new LinearInterpolation());
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.mowesta.android.app.view.interpolation;
|
||||
|
||||
/**
|
||||
* An interface to interpolate data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface IDataInterpolation {
|
||||
|
||||
/**
|
||||
* Computes an interpolated value between x and y that
|
||||
* resides at the specified fraction.
|
||||
*
|
||||
* @param x The x value.
|
||||
* @param y The y value.
|
||||
* @param fraction The fraction (between 0 = x and 1 = y).
|
||||
* @return The interpolated value.
|
||||
*/
|
||||
double interpolate(double x, double y, double fraction);
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.mowesta.android.app.view.interpolation;
|
||||
|
||||
/**
|
||||
* A simple linear interpolation.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LinearInterpolation implements IDataInterpolation {
|
||||
|
||||
@Override
|
||||
public double interpolate(double x, double y, double fraction) {
|
||||
return x + (y - x) * fraction;
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.mowesta.android.app.view.interpolation;
|
||||
|
||||
/**
|
||||
* An interpolation that does not compute intermediate values but
|
||||
* instead bases its decision on which value to return on the fraction,
|
||||
* creating a step function.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class StepInterpolation implements IDataInterpolation {
|
||||
|
||||
/**
|
||||
* The default threshold value that results in financial rounding.
|
||||
*/
|
||||
public static final double DEFAULT_THRESHOLD = 0.5;
|
||||
|
||||
/**
|
||||
* The threshold at which to switch.
|
||||
*/
|
||||
private double threshold;
|
||||
|
||||
/**
|
||||
* Creates an interpolation function with the default threshold.
|
||||
*/
|
||||
public StepInterpolation() {
|
||||
this(DEFAULT_THRESHOLD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new step interpolation with the specified
|
||||
* threshold.
|
||||
*
|
||||
* @param threshold The threshold that defines which
|
||||
* value to return.
|
||||
*/
|
||||
public StepInterpolation(double threshold) {
|
||||
this.threshold = threshold;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double interpolate(double x, double y, double fraction) {
|
||||
if (fraction < threshold) return x;
|
||||
else return y;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<gradient
|
||||
android:angle="0"
|
||||
android:endColor="#f8e9cf"
|
||||
android:centerColor="#ffffff"
|
||||
android:startColor="#f8e9cf"
|
||||
android:type="linear" />
|
||||
|
||||
</shape>
|
||||
@@ -0,0 +1,18 @@
|
||||
<vector android:height="24dp" android:viewportHeight="1576.68"
|
||||
android:viewportWidth="1576.68" android:width="24dp"
|
||||
xmlns:aapt="http://schemas.android.com/aapt" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:pathData="M788.34,788.34m-784.54,0a784.54,784.54 0,1 1,1569.08 0a784.54,784.54 0,1 1,-1569.08 0">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:startX="1577"
|
||||
android:startY="0"
|
||||
android:endX="0"
|
||||
android:endY="1577"
|
||||
android:startColor="#aaaaaaaa"
|
||||
android:endColor="#00ffffff"
|
||||
android:type="linear">
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path android:fillColor="#eeFFFFFF" android:pathData="M932.1,185.17c135.76,82 339.41,251.63 439.96,406.9 100.54,155.27 97.98,296.16 78.45,397.05 -19.53,100.88 -56.04,161.74 -83.9,133.57 -27.86,-28.18 -47.07,-145.4 -112.07,-279.53 -65,-134.13 -175.78,-285.17 -282.41,-409.44 -106.63,-124.27 -209.09,-221.77 -226.38,-273.33 -17.3,-51.57 50.59,-57.2 186.36,24.8z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<vector android:height="24dp" android:viewportHeight="30"
|
||||
android:tint="?attr/colorControlNormal"
|
||||
android:viewportWidth="30" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#FF000000" android:pathData="M4.61,16.88c0,-1.15 0.36,-2.17 1.08,-3.07c0.72,-0.9 1.63,-1.48 2.74,-1.73c0.31,-1.37 1.02,-2.49 2.11,-3.37s2.35,-1.32 3.76,-1.32c1.38,0 2.61,0.43 3.69,1.28s1.78,1.95 2.1,3.29h0.33c0.9,0 1.73,0.22 2.49,0.65s1.37,1.03 1.81,1.79c0.44,0.76 0.67,1.58 0.67,2.48c0,0.88 -0.21,1.7 -0.63,2.45s-1,1.35 -1.73,1.8c-0.73,0.45 -1.54,0.69 -2.41,0.72H9.41c-1.34,-0.06 -2.47,-0.57 -3.4,-1.53C5.08,19.37 4.61,18.22 4.61,16.88zM6.32,16.88c0,0.87 0.3,1.62 0.9,2.26s1.33,0.98 2.19,1.03h11.19c0.86,-0.04 1.59,-0.39 2.19,-1.03c0.61,-0.64 0.91,-1.4 0.91,-2.26c0,-0.88 -0.33,-1.63 -0.98,-2.27c-0.65,-0.64 -1.42,-0.96 -2.32,-0.96H18.8c-0.11,0 -0.17,-0.06 -0.17,-0.18l-0.07,-0.57c-0.11,-1.08 -0.58,-1.99 -1.4,-2.72c-0.82,-0.73 -1.77,-1.1 -2.86,-1.1c-1.09,0 -2.05,0.37 -2.85,1.1c-0.81,0.73 -1.27,1.64 -1.37,2.72l-0.08,0.57c0,0.12 -0.07,0.18 -0.2,0.18H9.27c-0.84,0.1 -1.54,0.46 -2.1,1.07S6.32,16.05 6.32,16.88z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<vector android:height="24dp" android:viewportHeight="30"
|
||||
android:tint="?attr/colorControlNormal"
|
||||
android:viewportWidth="30" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#FF000000" android:pathData="M7.56,17.19c0,-0.88 0.24,-1.89 0.72,-3.03s1.1,-2.25 1.86,-3.31c1.56,-2.06 2.92,-3.62 4.06,-4.67l0.75,-0.72c0.25,0.26 0.53,0.5 0.83,0.72c0.41,0.42 1.04,1.11 1.88,2.09s1.57,1.85 2.17,2.65c0.71,1.01 1.32,2.1 1.81,3.25s0.74,2.16 0.74,3.03c0,1 -0.19,1.95 -0.58,2.86c-0.39,0.91 -0.91,1.7 -1.57,2.36c-0.66,0.66 -1.45,1.19 -2.37,1.58c-0.92,0.39 -1.89,0.59 -2.91,0.59c-1,0 -1.95,-0.19 -2.86,-0.57c-0.91,-0.38 -1.7,-0.89 -2.36,-1.55c-0.66,-0.65 -1.19,-1.44 -1.58,-2.35S7.56,18.23 7.56,17.19zM9.82,14.26c0,0.83 0.17,1.49 0.52,1.99c0.35,0.49 0.88,0.74 1.59,0.74c0.72,0 1.25,-0.25 1.61,-0.74c0.35,-0.49 0.53,-1.15 0.54,-1.99c-0.01,-0.84 -0.19,-1.5 -0.54,-2c-0.35,-0.49 -0.89,-0.74 -1.61,-0.74c-0.71,0 -1.24,0.25 -1.59,0.74C9.99,12.76 9.82,13.42 9.82,14.26zM11.39,14.26c0,-0.15 0,-0.27 0,-0.35s0.01,-0.19 0.02,-0.33c0.01,-0.14 0.02,-0.25 0.05,-0.32s0.05,-0.16 0.09,-0.24c0.04,-0.08 0.09,-0.15 0.15,-0.18c0.07,-0.04 0.14,-0.06 0.23,-0.06c0.14,0 0.25,0.04 0.33,0.12s0.14,0.21 0.17,0.38c0.03,0.18 0.05,0.32 0.06,0.45s0.01,0.3 0.01,0.52c0,0.23 0,0.4 -0.01,0.52c-0.01,0.12 -0.03,0.27 -0.06,0.45c-0.03,0.17 -0.09,0.3 -0.17,0.38s-0.19,0.12 -0.33,0.12c-0.09,0 -0.16,-0.02 -0.23,-0.06c-0.07,-0.04 -0.12,-0.1 -0.15,-0.18c-0.04,-0.08 -0.07,-0.17 -0.09,-0.24c-0.02,-0.08 -0.04,-0.19 -0.05,-0.32c-0.01,-0.14 -0.02,-0.25 -0.02,-0.32S11.39,14.41 11.39,14.26zM11.98,22.01h1.32l4.99,-10.74h-1.35L11.98,22.01zM16.28,19.02c0.01,0.84 0.2,1.5 0.55,2c0.35,0.49 0.89,0.74 1.6,0.74c0.72,0 1.25,-0.25 1.6,-0.74c0.35,-0.49 0.52,-1.16 0.53,-2c-0.01,-0.84 -0.18,-1.5 -0.53,-1.99c-0.35,-0.49 -0.88,-0.74 -1.6,-0.74c-0.71,0 -1.25,0.25 -1.6,0.74C16.47,17.52 16.29,18.18 16.28,19.02zM17.85,19.02c0,-0.23 0,-0.4 0.01,-0.52c0.01,-0.12 0.03,-0.27 0.06,-0.45s0.09,-0.3 0.17,-0.38s0.19,-0.12 0.33,-0.12c0.09,0 0.17,0.02 0.24,0.06c0.07,0.04 0.12,0.1 0.16,0.19c0.04,0.09 0.07,0.17 0.1,0.24s0.04,0.18 0.05,0.32l0.01,0.32l0,0.34c0,0.16 0,0.28 0,0.35l-0.01,0.32l-0.05,0.32l-0.1,0.24l-0.16,0.19l-0.24,0.06c-0.14,0 -0.25,-0.04 -0.33,-0.12s-0.14,-0.21 -0.17,-0.38c-0.03,-0.18 -0.05,-0.33 -0.06,-0.45S17.85,19.25 17.85,19.02z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<vector android:height="24dp" android:viewportHeight="30"
|
||||
android:tint="?attr/colorControlNormal"
|
||||
android:viewportWidth="30" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#FF000000" android:pathData="M11.01,12.23c0,-0.26 0.13,-0.59 0.38,-1.01c0.25,-0.42 0.5,-0.77 0.73,-1.04c0.06,-0.07 0.14,-0.17 0.23,-0.28s0.15,-0.17 0.16,-0.18l0.37,0.43c0.28,0.31 0.53,0.66 0.76,1.07c0.23,0.41 0.35,0.74 0.35,1.01c0,0.41 -0.14,0.77 -0.43,1.06c-0.28,0.29 -0.63,0.44 -1.05,0.44c-0.41,0 -0.77,-0.15 -1.06,-0.44C11.16,12.99 11.01,12.64 11.01,12.23zM14.13,16.38c0,-0.29 0.08,-0.62 0.24,-1.01c0.16,-0.38 0.36,-0.74 0.6,-1.06c0.46,-0.61 0.89,-1.12 1.31,-1.53c0.04,-0.03 0.13,-0.11 0.26,-0.24l0.25,0.24c0.39,0.37 0.83,0.88 1.32,1.52c0.26,0.34 0.46,0.7 0.62,1.08s0.24,0.71 0.24,1c0,0.69 -0.23,1.26 -0.7,1.73c-0.47,0.47 -1.05,0.7 -1.73,0.7c-0.68,0 -1.25,-0.24 -1.72,-0.71S14.13,17.05 14.13,16.38zM15.65,9.48c0,-0.43 0.33,-1 1,-1.7l0.25,0.28c0.19,0.22 0.36,0.46 0.51,0.74c0.15,0.27 0.23,0.5 0.23,0.68c0,0.28 -0.1,0.5 -0.29,0.69c-0.19,0.18 -0.42,0.28 -0.7,0.28c-0.29,0 -0.53,-0.09 -0.72,-0.28C15.75,9.98 15.65,9.75 15.65,9.48z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24"
|
||||
android:tint="@color/primary">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M9,11.24V7.5C9,6.12 10.12,5 11.5,5S14,6.12 14,7.5v3.74c1.21,-0.81 2,-2.18 2,-3.74C16,5.01 13.99,3 11.5,3S7,5.01 7,7.5C7,9.06 7.79,10.43 9,11.24zM18.84,15.87l-4.54,-2.26c-0.17,-0.07 -0.35,-0.11 -0.54,-0.11H13v-6C13,6.67 12.33,6 11.5,6S10,6.67 10,7.5v10.74c-3.6,-0.76 -3.54,-0.75 -3.67,-0.75c-0.31,0 -0.59,0.13 -0.79,0.33l-0.79,0.8l4.94,4.94C9.96,23.83 10.34,24 10.75,24h6.79c0.75,0 1.33,-0.55 1.44,-1.28l0.75,-5.27c0.01,-0.07 0.02,-0.14 0.02,-0.2C19.75,16.63 19.37,16.09 18.84,15.87z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<vector android:height="24dp" android:viewportHeight="30"
|
||||
android:tint="?attr/colorControlNormal"
|
||||
android:viewportWidth="30" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#FF000000" android:pathData="M3.1,16.97c0,0.24 0.09,0.45 0.28,0.62c0.16,0.19 0.37,0.28 0.63,0.28H18.7c0.29,0 0.53,0.1 0.73,0.3c0.2,0.2 0.3,0.45 0.3,0.74c0,0.29 -0.1,0.53 -0.3,0.72c-0.2,0.19 -0.44,0.29 -0.74,0.29c-0.29,0 -0.54,-0.1 -0.73,-0.29c-0.16,-0.18 -0.36,-0.26 -0.6,-0.26c-0.25,0 -0.46,0.09 -0.64,0.26s-0.27,0.38 -0.27,0.61c0,0.25 0.09,0.46 0.28,0.63c0.56,0.55 1.22,0.83 1.96,0.83c0.78,0 1.45,-0.27 2.01,-0.81c0.56,-0.54 0.83,-1.19 0.83,-1.97s-0.28,-1.44 -0.84,-2c-0.56,-0.56 -1.23,-0.84 -2,-0.84H4.01c-0.25,0 -0.46,0.09 -0.64,0.26C3.19,16.51 3.1,16.72 3.1,16.97zM3.1,13.69c0,0.23 0.09,0.43 0.28,0.61c0.17,0.18 0.38,0.26 0.63,0.26h20.04c0.78,0 1.45,-0.27 2.01,-0.82c0.56,-0.54 0.84,-1.2 0.84,-1.97c0,-0.77 -0.28,-1.44 -0.84,-1.99s-1.23,-0.83 -2.01,-0.83c-0.77,0 -1.42,0.27 -1.95,0.8c-0.18,0.16 -0.27,0.38 -0.27,0.67c0,0.26 0.09,0.47 0.26,0.63c0.17,0.16 0.38,0.24 0.63,0.24c0.24,0 0.45,-0.08 0.63,-0.24c0.19,-0.21 0.42,-0.31 0.7,-0.31c0.29,0 0.53,0.1 0.73,0.3c0.2,0.2 0.3,0.44 0.3,0.73c0,0.29 -0.1,0.53 -0.3,0.72c-0.2,0.19 -0.44,0.29 -0.73,0.29H4.01c-0.25,0 -0.46,0.09 -0.64,0.26C3.19,13.23 3.1,13.44 3.1,13.69z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:id="@android:id/background">
|
||||
<color android:color="#33363636" />
|
||||
</item>
|
||||
<item android:id="@android:id/progress">
|
||||
<clip
|
||||
android:clipOrientation="vertical"
|
||||
android:gravity="bottom">
|
||||
<shape>
|
||||
<gradient
|
||||
android:startColor="#f9a825"
|
||||
android:centerColor="#f9a825"
|
||||
android:endColor="#f9a825"
|
||||
android:angle="90" />
|
||||
</shape>
|
||||
</clip>
|
||||
</item>
|
||||
</layer-list>
|
||||
@@ -0,0 +1,285 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<data>
|
||||
<variable
|
||||
name="model"
|
||||
type="com.mowesta.android.feign.model.WeatherCondition" />
|
||||
</data>
|
||||
|
||||
<androidx.core.widget.NestedScrollView
|
||||
app:layout_behavior="@string/appbar_scrolling_view_behavior"
|
||||
android:fillViewport="true"
|
||||
android:id="@+id/gradient_scroll"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<LinearLayout
|
||||
android:baselineAligned="false"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<LinearLayout
|
||||
android:orientation="vertical"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="match_parent">
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:contentDescription="@string/label_temperature"
|
||||
app:srcCompat="@drawable/ic_thermometer_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="22dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:contentDescription="@string/label_precipitation"
|
||||
app:srcCompat="@drawable/ic_raindrops_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:contentDescription="@string/label_cloud_coverage"
|
||||
app:srcCompat="@drawable/ic_cloud_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:padding="4dp"
|
||||
android:contentDescription="@string/label_local_time"
|
||||
app:srcCompat="@drawable/ic_alarm_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:padding="2dp"
|
||||
android:contentDescription="@string/label_humidity"
|
||||
app:srcCompat="@drawable/ic_humidity_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:contentDescription="@string/label_wind_speed"
|
||||
app:srcCompat="@drawable/ic_wind_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:contentDescription="@string/label_pressure"
|
||||
app:srcCompat="@drawable/ic_barometer_normal_24"/>
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.constraintlayout.widget.ConstraintLayout
|
||||
android:id="@+id/gradient_constraint"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<LinearLayout
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<com.mowesta.android.app.view.GradientView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_temperature"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.mowesta.android.app.view.DropView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_preciptiation"
|
||||
android:background="@drawable/bg_precipitation"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.mowesta.android.app.view.DualGradientView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_cloud"
|
||||
android:background="@color/bg_cloud"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.mowesta.android.app.view.TimeView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_touch"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.mowesta.android.app.view.GradientView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_humidity"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.mowesta.android.app.view.ParticleView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_wind_speed"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.mowesta.android.app.view.GradientView
|
||||
app:direction="HORIZONTAL"
|
||||
android:id="@+id/gradient_pressure"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.constraintlayout.widget.Guideline
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:id="@+id/guide_gradient"
|
||||
app:layout_constraintGuide_percent="0.5"
|
||||
android:orientation="vertical"/>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/gradient_text"
|
||||
app:layout_constraintLeft_toLeftOf="@id/guide_gradient"
|
||||
android:background="@color/normal"
|
||||
android:orientation="horizontal"
|
||||
android:layout_width="160dp"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/gradient_progress_1"
|
||||
android:layout_width="2dp"
|
||||
android:background="@color/normal"
|
||||
android:layout_height="match_parent"
|
||||
android:progressDrawable="@drawable/progress_vertical"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:indeterminate="false" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"
|
||||
android:paddingStart="@dimen/space_medium"
|
||||
android:paddingEnd="@dimen/space_medium"
|
||||
android:orientation="vertical">
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="7°C"
|
||||
temperature="@{model}"
|
||||
android:textStyle="bold"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="11mm/h"
|
||||
precipitation="@{model}"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="99%"
|
||||
cloudCoverage="@{model}"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="1.1.2000 11:00"
|
||||
android:id="@+id/gradient_time"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="99%"
|
||||
humidity="@{model}"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="4km/h"
|
||||
windSpeed="@{model}"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="1000.3hPa"
|
||||
pressure="@{model}"
|
||||
android:gravity="center"
|
||||
android:layout_gravity="center"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"/>
|
||||
</LinearLayout>
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/gradient_progress_2"
|
||||
android:layout_width="2dp"
|
||||
android:background="@color/normal"
|
||||
android:layout_height="match_parent"
|
||||
android:scaleY="-1"
|
||||
android:progressDrawable="@drawable/progress_vertical"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:indeterminate="false" />
|
||||
</LinearLayout>
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</layout>
|
||||
@@ -38,7 +38,7 @@
|
||||
<com.google.android.material.bottomnavigation.BottomNavigationView
|
||||
android:id="@+id/bottom_navigation"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_height="48dp"
|
||||
android:layout_gravity="bottom"
|
||||
android:background="@color/primary"
|
||||
app:itemIconTint="@drawable/selector_navigation"
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<data>
|
||||
<variable
|
||||
name="model"
|
||||
type="com.mowesta.android.feign.model.WeatherCondition" />
|
||||
</data>
|
||||
|
||||
<androidx.core.widget.NestedScrollView
|
||||
app:layout_behavior="@string/appbar_scrolling_view_behavior"
|
||||
android:fillViewport="true"
|
||||
android:id="@+id/gradient_scroll"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:orientation="horizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
<ImageView
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/label_temperature"
|
||||
app:srcCompat="@drawable/ic_thermometer_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/label_precipitation"
|
||||
app:srcCompat="@drawable/ic_raindrops_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/label_cloud_coverage"
|
||||
app:srcCompat="@drawable/ic_cloud_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="24dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:padding="4dp"
|
||||
android:contentDescription="@string/label_local_time"
|
||||
app:srcCompat="@drawable/ic_alarm_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="24dp"
|
||||
android:padding="2dp"
|
||||
android:contentDescription="@string/label_humidity"
|
||||
app:srcCompat="@drawable/ic_humidity_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/label_wind_speed"
|
||||
app:srcCompat="@drawable/ic_wind_normal_24"/>
|
||||
<ImageView
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="24dp"
|
||||
android:contentDescription="@string/label_pressure"
|
||||
app:srcCompat="@drawable/ic_barometer_normal_24"/>
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.constraintlayout.widget.ConstraintLayout
|
||||
android:id="@+id/gradient_constraint"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<LinearLayout
|
||||
android:orientation="horizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<com.mowesta.android.app.view.GradientView
|
||||
android:id="@+id/gradient_temperature"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
<com.mowesta.android.app.view.DropView
|
||||
android:id="@+id/gradient_preciptiation"
|
||||
android:background="@drawable/bg_precipitation"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
<com.mowesta.android.app.view.DualGradientView
|
||||
android:id="@+id/gradient_cloud"
|
||||
android:background="@color/bg_cloud"
|
||||
android:layout_width="0dp"
|
||||
android:layout_weight="1"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
|
||||
<com.mowesta.android.app.view.TimeView
|
||||
android:id="@+id/gradient_touch"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
|
||||
<com.mowesta.android.app.view.GradientView
|
||||
android:id="@+id/gradient_humidity"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
<com.mowesta.android.app.view.ParticleView
|
||||
android:id="@+id/gradient_wind_speed"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
<com.mowesta.android.app.view.GradientView
|
||||
android:id="@+id/gradient_pressure"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<androidx.constraintlayout.widget.Guideline
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:id="@+id/guide_gradient"
|
||||
app:layout_constraintGuide_percent="0.5"
|
||||
android:orientation="horizontal"/>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/gradient_text"
|
||||
app:layout_constraintBottom_toTopOf="@id/guide_gradient"
|
||||
android:background="@color/normal"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/gradient_progress_1"
|
||||
android:layout_width="match_parent"
|
||||
android:background="@color/normal"
|
||||
android:foregroundGravity="center_vertical"
|
||||
android:layout_height="2dp"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:indeterminate="false" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<Space
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="11mm/h"
|
||||
precipitation="@{model}"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:gravity="center_horizontal|bottom"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="Donnerstag | 11:00"
|
||||
android:id="@+id/gradient_time"
|
||||
android:singleLine="true"
|
||||
android:ellipsize="middle"
|
||||
android:gravity="center_horizontal|bottom"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="4km/h"
|
||||
windSpeed="@{model}"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center_horizontal|bottom"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
<Space
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="0dp"/>
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
|
||||
|
||||
<Space
|
||||
android:layout_width="8dp"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="7°C"
|
||||
temperature="@{model}"
|
||||
android:textStyle="bold"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:gravity="start|bottom"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:layout_weight="1.5"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="99%"
|
||||
cloudCoverage="@{model}"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:gravity="end|bottom"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
<Space
|
||||
android:layout_width="64dp"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="99%"
|
||||
humidity="@{model}"
|
||||
android:gravity="start|bottom"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:layout_weight="1"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
|
||||
<com.google.android.material.textview.MaterialTextView
|
||||
tools:text="1000.3hPa"
|
||||
pressure="@{model}"
|
||||
android:gravity="end|bottom"
|
||||
android:maxLines="1"
|
||||
android:ellipsize="end"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption"
|
||||
android:layout_weight="1.5"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
<Space
|
||||
android:layout_width="8dp"
|
||||
android:layout_height="0dp"/>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/gradient_progress_2"
|
||||
android:layout_width="match_parent"
|
||||
android:background="@color/normal"
|
||||
android:foregroundGravity="center_vertical"
|
||||
android:layout_height="2dp"
|
||||
android:scaleX="-1"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:indeterminate="false" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
</androidx.core.widget.NestedScrollView>
|
||||
</layout>
|
||||
@@ -2,6 +2,7 @@
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
app:layout_behavior="@string/appbar_scrolling_view_behavior"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
@@ -11,6 +12,7 @@
|
||||
app:tabMaxWidth="0dp"
|
||||
app:tabGravity="fill"
|
||||
app:tabMode="fixed"
|
||||
app:tabTextAppearance="@style/TextAppearance.Mowesta.TabLayout"
|
||||
tools:targetApi="21"
|
||||
android:elevation="4dp"
|
||||
android:layout_width="match_parent"
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
android:layout_height="match_parent"
|
||||
android:padding="8dp"
|
||||
app:srcCompat="@drawable/icon_launch_sun"
|
||||
android:fitsSystemWindows="true"
|
||||
android:scaleType="fitEnd"
|
||||
app:layout_collapseMode="parallax" />
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
<com.google.android.material.appbar.AppBarLayout
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:theme="@style/ThemeOverlay.MaterialComponents.Dark"
|
||||
android:id="@+id/layout_appbar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="128dp">
|
||||
|
||||
@@ -44,5 +46,8 @@
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="?attr/actionBarSize"
|
||||
app:layout_collapseMode="pin" />
|
||||
|
||||
|
||||
</com.google.android.material.appbar.CollapsingToolbarLayout>
|
||||
|
||||
</com.google.android.material.appbar.AppBarLayout>
|
||||
@@ -10,15 +10,10 @@
|
||||
type="com.mowesta.android.app.model.VideoViewModel.OnVideoSelectedListener" />
|
||||
</data>
|
||||
<LinearLayout
|
||||
android:layout_margin="8dp"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical">
|
||||
<LinearLayout
|
||||
android:layout_margin="8dp"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
<ImageView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
@@ -41,7 +36,6 @@
|
||||
android:ellipsize="end"
|
||||
android:singleLine="true"
|
||||
android:textAppearance="?attr/textAppearanceCaption" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
</layout>
|
||||
|
||||
@@ -228,8 +228,9 @@
|
||||
<string name="city_video">Videos</string>
|
||||
<string name="city_info">Informationen</string>
|
||||
<string name="city_info_title">Aktuelles Wetter</string>
|
||||
<string name="city_info_gradient">Visuell</string>
|
||||
<string name="city_info_day">Tag</string>
|
||||
<string name="city_info_time">Tageszeit</string>
|
||||
<string name="city_info_time">Zeitraum</string>
|
||||
<string name="city_info_hour">Stunde</string>
|
||||
<string name="label_station">Wetterstation</string>
|
||||
<string name="label_full_day">Gesamter Tag</string>
|
||||
|
||||
@@ -3,4 +3,7 @@
|
||||
<color name="separator">#555555</color>
|
||||
<color name="bg_search">#333333</color>
|
||||
<color name="inverse">#a0ffffff</color>
|
||||
<color name="normal">#ff000000</color>
|
||||
<color name="particle">#ff4444ff</color>
|
||||
|
||||
</resources>
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<declare-styleable name="DataView">
|
||||
<attr name="direction" format="enum">
|
||||
<enum name="HORIZONTAL" value="0" />
|
||||
<enum name="VERTICAL" value="1" />
|
||||
</attr>
|
||||
</declare-styleable>
|
||||
|
||||
<declare-styleable name="WeatherView">
|
||||
<attr name="weather" format="enum">
|
||||
<enum name="DAY_SUNNY" value="0"/>
|
||||
|
||||
@@ -10,5 +10,21 @@
|
||||
<color name="separator">#eeeeee</color>
|
||||
<color name="bg_search">#fefefe</color>
|
||||
<color name="inverse">#a0000000</color>
|
||||
<color name="normal">#ffffffff</color>
|
||||
<color name="particle">#ff0000ff</color>
|
||||
<color name="fg_accent">#c0000000</color>
|
||||
|
||||
<color name="bg_cloud">#5c99e9</color>
|
||||
|
||||
<!--
|
||||
0xFFEFF8FD, // 1 ice
|
||||
0xFF989278, // 2 rock
|
||||
0xFFD1B281, // 3 sand
|
||||
0xFFE3CCAB, // 4 sandyloam
|
||||
0xFFCD9160, // 5 loam
|
||||
0xFFB65941, // 6 clayloam
|
||||
0xFFAC753B, // 7 clay
|
||||
0xFF987E6F, // 8 peat
|
||||
0xFF47859c, // 9 sea water
|
||||
-->
|
||||
</resources>
|
||||
|
||||
@@ -231,6 +231,7 @@
|
||||
<string name="city_video">Video</string>
|
||||
<string name="city_info">Information</string>
|
||||
<string name="city_info_title">Current Weather</string>
|
||||
<string name="city_info_gradient">Visual</string>
|
||||
<string name="city_info_day">Day</string>
|
||||
<string name="city_info_time">Time</string>
|
||||
<string name="city_info_hour">Hour</string>
|
||||
|
||||
@@ -29,4 +29,9 @@
|
||||
|
||||
<style name="ThemeOverlay.Mowesta.MaterialComponents" parent="Theme.MaterialComponents.Light" />
|
||||
|
||||
|
||||
<style name="TextAppearance.Mowesta.TabLayout" parent="TextAppearance.MaterialComponents.Button">
|
||||
<item name="android:letterSpacing" tools:targetApi="21">0</item>
|
||||
</style>
|
||||
|
||||
</resources>
|
||||
|
||||
@@ -220,11 +220,11 @@ public abstract class SdkService extends Service {
|
||||
public void onCreate() {
|
||||
Log.d(TAG, "Creating sdk service.");
|
||||
super.onCreate();
|
||||
repository = SdkRepository.getInstance(this.getApplication());
|
||||
capabilityManager = new CapabilityManager(getApplication());
|
||||
channelManager = new ChannelManager(getApplication());
|
||||
channelManager.createChannel();
|
||||
startForeground(channelManager.getNotificationId(), channelManager.createNotification(R.string.mowesta_sdk_notification_content_idle));
|
||||
repository = SdkRepository.getInstance(this.getApplication());
|
||||
capabilityManager = new CapabilityManager(getApplication());
|
||||
repository.getUploading().observeForever(uploadListener);
|
||||
locationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
|
||||
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
|
||||
@@ -635,6 +635,10 @@ public abstract class SdkService extends Service {
|
||||
// cleanup based on type
|
||||
if (currentState == State.GPS) cleanupGps();
|
||||
if (currentState == State.NET) cleanupNet();
|
||||
// workaround locations that might be buffered already
|
||||
// in the location listeners buffer which can cause
|
||||
// two locations to be sent despite deactivation
|
||||
if (measurement == null) return;
|
||||
Coordinate c = new Coordinate();
|
||||
c.setLatitude(location.getLatitude());
|
||||
c.setLongitude(location.getLongitude());
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ allprojects {
|
||||
|
||||
// set version for our project
|
||||
group = 'com.mowesta'
|
||||
version = '1.0.7'
|
||||
version = '1.0.9'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
2C2CA271237304E200529274 /* MowestaApi in Frameworks */ = {isa = PBXBuildFile; productRef = 2C2CA270237304E200529274 /* MowestaApi */; };
|
||||
2C32C47524B355A500B69113 /* SwiftUICharts in Frameworks */ = {isa = PBXBuildFile; productRef = 2C32C47424B355A500B69113 /* SwiftUICharts */; };
|
||||
2C7846D52372F44300766694 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7846D42372F44300766694 /* AppDelegate.swift */; };
|
||||
2C7846D72372F44300766694 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7846D62372F44300766694 /* SceneDelegate.swift */; };
|
||||
2C7846D92372F44300766694 /* MainTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7846D82372F44300766694 /* MainTabView.swift */; };
|
||||
@@ -303,6 +304,7 @@
|
||||
9E6D641223CCC2600002CBCF /* Socket in Frameworks */,
|
||||
9E0D267223AD2E7D00BE14F5 /* AuthenticationServices.framework in Frameworks */,
|
||||
9E6D640623CC73320002CBCF /* NetworkExtension.framework in Frameworks */,
|
||||
2C32C47524B355A500B69113 /* SwiftUICharts in Frameworks */,
|
||||
9E3BCD3623ACED50002F2D8F /* KeychainSwift in Frameworks */,
|
||||
2C2CA271237304E200529274 /* MowestaApi in Frameworks */,
|
||||
);
|
||||
@@ -695,6 +697,7 @@
|
||||
2C2CA270237304E200529274 /* MowestaApi */,
|
||||
9E3BCD3523ACED50002F2D8F /* KeychainSwift */,
|
||||
9E6D641123CCC2600002CBCF /* Socket */,
|
||||
2C32C47424B355A500B69113 /* SwiftUICharts */,
|
||||
);
|
||||
productName = app;
|
||||
productReference = 2C7846D12372F44300766694 /* MoWeSta.app */;
|
||||
@@ -772,6 +775,7 @@
|
||||
packageReferences = (
|
||||
9E3BCD3423ACED50002F2D8F /* XCRemoteSwiftPackageReference "keychain-swift" */,
|
||||
9E6D641023CCC2600002CBCF /* XCRemoteSwiftPackageReference "BlueSocket" */,
|
||||
2C32C47324B355A500B69113 /* XCRemoteSwiftPackageReference "ChartView" */,
|
||||
);
|
||||
productRefGroup = 2C7846D22372F44300766694 /* Products */;
|
||||
projectDirPath = "";
|
||||
@@ -1294,6 +1298,14 @@
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
2C32C47324B355A500B69113 /* XCRemoteSwiftPackageReference "ChartView" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/AppPear/ChartView";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 1.5.3;
|
||||
};
|
||||
};
|
||||
9E3BCD3423ACED50002F2D8F /* XCRemoteSwiftPackageReference "keychain-swift" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/evgenyneu/keychain-swift.git";
|
||||
@@ -1321,6 +1333,11 @@
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = MowestaApi;
|
||||
};
|
||||
2C32C47424B355A500B69113 /* SwiftUICharts */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 2C32C47324B355A500B69113 /* XCRemoteSwiftPackageReference "ChartView" */;
|
||||
productName = SwiftUICharts;
|
||||
};
|
||||
9E3BCD3523ACED50002F2D8F /* KeychainSwift */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 9E3BCD3423ACED50002F2D8F /* XCRemoteSwiftPackageReference "keychain-swift" */;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import os
|
||||
import Foundation
|
||||
import KeychainSwift
|
||||
import UIKit
|
||||
import MowestaApi
|
||||
|
||||
/*
|
||||
@@ -83,7 +84,8 @@ class UserData: ObservableObject {
|
||||
if !DeviceData.shared.created {
|
||||
resetDeviceForPairing()
|
||||
} else {
|
||||
DeviceAPI.setCurrentDeviceUser(completion: { d, err in
|
||||
let d = Device(_id: DeviceData.shared.idInt64, creationTime: 0, modificationTime: 0, deleted: false, user: nil, os: .ios, manufacturer: "Apple Inc.", device: UIDevice.current.modelName, model: UIDevice.current.model)
|
||||
DeviceAPI.setCurrentDeviceUser(body: d, completion: { d, err in
|
||||
if let error = err {
|
||||
switch(error as! ErrorResponse) {
|
||||
case .error(let statusCode, _, _):
|
||||
|
||||
@@ -47,7 +47,7 @@ class MeasurementService {
|
||||
if let c = coordinate {
|
||||
let measurement = MowestaApi.Measurement(coordinate: c, time: timestamp, measurements: measurementData, deviceId: DeviceData.shared.idInt64)
|
||||
|
||||
DeviceAPI.addCurrentDeviceMeasurements(body: MeasurementBatch(elements: [measurement]), completion: { _,err in
|
||||
DeviceAPI.addCurrentDeviceMeasurements(body: [measurement], completion: { _,err in
|
||||
if let error = err {
|
||||
NSLog("\(error)")
|
||||
} else {
|
||||
|
||||
@@ -7,6 +7,8 @@ import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.render.VideoFrameComposer;
|
||||
import com.mowesta.data.dwd.render.VideoImageRenderer;
|
||||
import com.mowesta.data.process.projection.CroppedProjection;
|
||||
import com.mowesta.data.process.projection.CroppedProjection.CropType;
|
||||
import com.mowesta.data.process.projection.IProjection;
|
||||
@@ -124,11 +126,11 @@ public class VideoConfiguration {
|
||||
* @return The frame composer.
|
||||
* @throws IOException Thrown if the longitudes or latitudes cannot be loaded.
|
||||
*/
|
||||
public FrameComposer createComposer(Time time) throws IOException {
|
||||
public VideoFrameComposer createComposer(Time time) throws IOException {
|
||||
IProjection projection = new CroppedProjection(new MercatorProjection(), CropType.COORDINATE, minLongitude, maxLatitude, maxLongitude, minLatitude);
|
||||
ImageGenerator generator = new ImageGenerator(prediction.getLongitues(time), prediction.getLatitudes(time), projection, imageWidth, imageHeight);
|
||||
VideoImageRenderer generator = new VideoImageRenderer(prediction.getLongitues(time), prediction.getLatitudes(time), projection, imageWidth, imageHeight);
|
||||
generator.getBoundaryRenderer().setColor(new Color(0xC0f9a825, true));
|
||||
FrameComposer result = new FrameComposer(generator, createOverlay(generator), frameWidth, frameHeight);
|
||||
VideoFrameComposer result = new VideoFrameComposer(generator, createOverlay(generator), frameWidth, frameHeight);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -138,7 +140,7 @@ public class VideoConfiguration {
|
||||
* @param generator The generator.
|
||||
* @return The overlay image.
|
||||
*/
|
||||
private BufferedImage createOverlay(ImageGenerator generator) {
|
||||
private BufferedImage createOverlay(VideoImageRenderer generator) {
|
||||
switch (prediction.getType()) {
|
||||
case COSMO_EUROPE:
|
||||
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
package com.mowesta.data.dwd;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.video.PixelFormat;
|
||||
import com.mowesta.data.process.video.VideoEncoder;
|
||||
import com.mowesta.data.dwd.render.AbstractVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.CloudVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.PrecipitationVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.PressureVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.TemperatureVideoRenderer;
|
||||
import com.mowesta.data.dwd.render.VideoFrameComposer;
|
||||
import com.mowesta.data.process.video.VideoEncoder.Quality;
|
||||
import com.mowesta.data.process.video.VideoFrame;
|
||||
import com.mowesta.data.process.video.VideoInterpolator;
|
||||
import com.mowesta.data.process.video.VideoInterpolator.Type;
|
||||
|
||||
/**
|
||||
* A generator for videos.
|
||||
@@ -58,7 +54,7 @@ public class VideoGenerator {
|
||||
/**
|
||||
* The frame composer.
|
||||
*/
|
||||
protected FrameComposer composer;
|
||||
protected VideoFrameComposer composer;
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
@@ -71,9 +67,9 @@ public class VideoGenerator {
|
||||
protected Quality quality = Quality.MEDIUM;
|
||||
|
||||
/**
|
||||
* The video encoder bitrate.
|
||||
* The video encoder crf value between 0 (lossless) and 51 (compressed).
|
||||
*/
|
||||
protected int bitRate = 750;
|
||||
protected int crf = 24;
|
||||
|
||||
/**
|
||||
* The frames per second.
|
||||
@@ -86,11 +82,30 @@ public class VideoGenerator {
|
||||
* @param prediction The prediction.
|
||||
* @param composer The composer for frames.
|
||||
*/
|
||||
public VideoGenerator(NumericPrediction prediction, FrameComposer composer) {
|
||||
public VideoGenerator(NumericPrediction prediction, VideoFrameComposer composer) {
|
||||
this.prediction = prediction;
|
||||
this.composer = composer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the prediction.
|
||||
*
|
||||
* @return The prediction.
|
||||
*/
|
||||
public NumericPrediction getPrediction() {
|
||||
return prediction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the frame composer.
|
||||
*
|
||||
* @return The frame composer.
|
||||
*/
|
||||
public VideoFrameComposer getComposer() {
|
||||
return composer;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the quality.
|
||||
*
|
||||
@@ -110,21 +125,21 @@ public class VideoGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the bitRate.
|
||||
* Returns the crf.
|
||||
*
|
||||
* @return The bitRate.
|
||||
* @return The crf.
|
||||
*/
|
||||
public int getBitRate() {
|
||||
return bitRate;
|
||||
public int getCrf() {
|
||||
return crf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the bitRate.
|
||||
* Sets the crf.
|
||||
*
|
||||
* @param bitRate The bitRate to set.
|
||||
* @param crf The crf to set.
|
||||
*/
|
||||
public void setBitRate(int bitRate) {
|
||||
this.bitRate = bitRate;
|
||||
public void setCrf(int crf) {
|
||||
this.crf = crf;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,117 +159,6 @@ public class VideoGenerator {
|
||||
public void setFps(int fps) {
|
||||
this.fps = fps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a base layer using the soil type, plant cover and surface height.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @return The base layer.
|
||||
* @throws IOException Thrown if something cannot be loaded.
|
||||
*/
|
||||
protected BufferedImage getBaseLayer(Variable variable, Time time) throws IOException {
|
||||
BufferedImage result = composer.createImage();
|
||||
switch (variable) {
|
||||
case T2M:
|
||||
case PMSL:
|
||||
break;
|
||||
default:
|
||||
composer.getGenerator().renderSoilType(result, prediction.getValues(prediction.getFile(Variable.SOILTYP, time)));
|
||||
BufferedImage temp = composer.createImage();
|
||||
composer.getGenerator().renderPlantCover(temp, prediction.getValues(prediction.getFile(Variable.PLCOV, time)));
|
||||
composer.renderImage(result, temp);
|
||||
composer.getGenerator().renderSurfaceHeight(temp, prediction.getValues(prediction.getFile(Variable.HSURF, time)));
|
||||
composer.renderImage(result, temp);
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a data layer for a particular hour, if the data is available.
|
||||
*
|
||||
* @param image The image used for rendering.
|
||||
* @param time The time.
|
||||
* @param hour The hour.
|
||||
* @param variable The variable.
|
||||
* @return True if the image has been created, false if the data is not available.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected boolean getDataLayer(BufferedImage image, Variable variable, Time time, int hour) throws IOException {
|
||||
DoubleArray data = null;
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
case T2M:
|
||||
case CLCT:
|
||||
File f = prediction.getFile(variable, time, hour);
|
||||
if (f != null) data = prediction.getValues(f);
|
||||
break;
|
||||
case PREC:
|
||||
File f1 = prediction.getFile(variable, time, hour);
|
||||
File f2 = prediction.getFile(variable, time, hour + 1);
|
||||
if (f1 != null && f2 != null) {
|
||||
data = prediction.getValues(f2);
|
||||
DoubleArray base = prediction.getValues(f1);
|
||||
for (int i = 0, s = data.getSize(); i < s; i++) {
|
||||
data.setValue(i, data.getValue(i) - base.getValue(i));
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (data != null) {
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
composer.getGenerator().renderPressure(image, data);
|
||||
return true;
|
||||
case T2M:
|
||||
composer.getGenerator().renderTemperature(image, data);
|
||||
return true;
|
||||
case CLCT:
|
||||
File f = prediction.getFile(Variable.CLDEPTH, time, hour);
|
||||
if (f != null) {
|
||||
composer.getGenerator().renderCloudCoverage3D(image, data, prediction.getValues(f));
|
||||
} else {
|
||||
composer.getGenerator().renderCloudCoverage(image, data);
|
||||
}
|
||||
return true;
|
||||
case PREC:
|
||||
composer.getGenerator().renderPrecipitation(image, data);
|
||||
return true;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an overlay layer using the boundary renderer.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @return The overlay layer.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected BufferedImage getOverlayLayer(Variable variable, Time time) throws IOException {
|
||||
BufferedImage result = composer.createImage();
|
||||
composer.getGenerator().renderBoundaries(result, false);
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
case T2M:
|
||||
BufferedImage temp = composer.createImage();
|
||||
composer.getGenerator().renderSurfaceHeight(temp, prediction.getValues(prediction.getFile(Variable.HSURF, time)));
|
||||
composer.renderImage(result, temp);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the video types.
|
||||
@@ -267,21 +171,6 @@ public class VideoGenerator {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the interpolation type for the variable.
|
||||
*
|
||||
* @param variable The variable.
|
||||
* @return The interpolation type for the variable.
|
||||
*/
|
||||
protected VideoInterpolator.Type getInterpolation(Variable variable) {
|
||||
switch (variable) {
|
||||
case CLCT:
|
||||
case PREC:
|
||||
return Type.MOTION;
|
||||
default:
|
||||
return Type.BLEND;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a video and stores it in the destination video file together with
|
||||
@@ -299,121 +188,40 @@ public class VideoGenerator {
|
||||
*/
|
||||
public void createVideo(Variable variable, Time time, int first, int last, File video, File preview, IProgressMonitor monitor) throws IOException {
|
||||
final IProgressMonitor m = monitor==null?MONITOR_NULL:monitor;
|
||||
// initialize all the buffers that we need
|
||||
BufferedImage baseLayer = getBaseLayer(variable, time);
|
||||
BufferedImage overlayLayer = getOverlayLayer(variable, time);
|
||||
BufferedImage input = composer.createImage();
|
||||
BufferedImage image = composer.createImage();
|
||||
BufferedImage frame = composer.createFrame(BufferedImage.TYPE_INT_ARGB);
|
||||
BufferedImage dataLayer = composer.createImage();
|
||||
int[] counter = new int[2]; // key frame, interpolate frame
|
||||
boolean[] canceled = new boolean[1];
|
||||
byte[] imageBuffer = VideoFrame.createBuffer(composer.getGenerator().getWidth(), composer.getGenerator().getHeight(), PixelFormat.ARGB);
|
||||
byte[] frameBuffer = VideoFrame.createBuffer(composer.getWidth(), composer.getHeight(), PixelFormat.ARGB);
|
||||
// create the encoder and interpolator
|
||||
VideoEncoder encoder = new VideoEncoder(composer.getWidth(), composer.getHeight(), PixelFormat.ARGB, 30, bitRate, quality);
|
||||
try {
|
||||
VideoInterpolator interpolator = new VideoInterpolator(composer.getGenerator().getWidth(), composer.getGenerator().getHeight(), PixelFormat.ARGB, 1, 32, getInterpolation(variable));
|
||||
try {
|
||||
// create a frame callback that forwards frames from interpolator to encoder
|
||||
VideoInterpolator.FrameCallback handler = (source, pts, data) -> {
|
||||
if (canceled[0]) return;
|
||||
logger.log(Level.FINE, "Received interpolated frame of " + prediction.getType() + "-" + variable + ".");
|
||||
VideoFrame.decodeImage(PixelFormat.ARGB, data, dataLayer);
|
||||
composer.renderImage(image, baseLayer);
|
||||
composer.renderImage(image, dataLayer);
|
||||
composer.renderImage(image, overlayLayer);
|
||||
composer.renderFrame(frame, image);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, frameBuffer);
|
||||
try {
|
||||
// drop 1 frame at the beginning and one at the end for smoother motion
|
||||
int f = (int)(pts % 32);
|
||||
if (f < 31 && f > 0) {
|
||||
counter[1] += 1;
|
||||
logger.log(Level.FINE, "Encoding interpolated frame for pts " + counter[1] + " of " + prediction.getType() + "-" + variable + ".");
|
||||
encoder.addFrame(frameBuffer);
|
||||
canceled[0] = canceled[0] || m.onFrameProcessed(counter[0], counter[1]);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to encode image.", e);
|
||||
}
|
||||
};
|
||||
for (int i = first; i <= last; i++) {
|
||||
logger.log(Level.INFO, "Generating key frame for hour " + i + " of " + prediction.getType() + "-" + variable + ".");
|
||||
if (getDataLayer(input, variable, time, i)) {
|
||||
if (counter[0] == 0) {
|
||||
String format = guessPreviewFormat(preview);
|
||||
logger.log(Level.INFO, "Generating preview image as '" + format + "' in '" + preview.getAbsolutePath() + "'.");
|
||||
BufferedImage output = format.equals("png")?frame:composer.createFrame(BufferedImage.TYPE_INT_RGB);
|
||||
composer.renderImage(image, baseLayer);
|
||||
composer.renderImage(image, input);
|
||||
composer.renderImage(image, overlayLayer);
|
||||
composer.renderFrame(output, image);
|
||||
ImageIO.write(output, format , preview);
|
||||
}
|
||||
counter[0] += 1;
|
||||
canceled[0] = canceled[0] || m.onFrameProcessed(counter[0], counter[1]);
|
||||
if (canceled[0]) throw new IOException("Video generation canceled.");
|
||||
logger.log(Level.FINE, "Interpolating key frame for hour " + i + " of " + prediction.getType() + "-" + variable + ".");
|
||||
VideoFrame.encodeImage(input, PixelFormat.ARGB, imageBuffer);
|
||||
interpolator.addFrame(i, imageBuffer, handler);
|
||||
if (canceled[0]) throw new IOException("Video generation canceled.");
|
||||
} else {
|
||||
logger.log(Level.SEVERE, "Failed to generate key frame for hour " + i + " of " + prediction.getType() + "-" + variable + ".");
|
||||
}
|
||||
}
|
||||
if (canceled[0]) throw new IOException("Video generation canceled for " + prediction.getType() + "-" + variable + ".");
|
||||
VideoFrame.encodeImage(input, PixelFormat.ARGB, imageBuffer);
|
||||
interpolator.addFrame(last + 1, imageBuffer, handler);
|
||||
interpolator.release();
|
||||
logger.log(Level.INFO, "Remultiplexing video of " + prediction.getType() + "-" + variable + ".");
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
interpolator.release();
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
AbstractVideoRenderer renderer;
|
||||
switch (variable) {
|
||||
case PMSL:
|
||||
renderer = new PressureVideoRenderer(this, time, getIsobars());
|
||||
break;
|
||||
case T2M:
|
||||
renderer = new TemperatureVideoRenderer(this, time, getIsotherms());
|
||||
break;
|
||||
case CLCT:
|
||||
renderer = new CloudVideoRenderer(this, time);
|
||||
break;
|
||||
case PREC:
|
||||
renderer = new PrecipitationVideoRenderer(this, time);
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Unsupported video type " + variable + ".");
|
||||
}
|
||||
renderer.renderPreview(preview, first);
|
||||
renderer.renderVideo(video, first, last, m);
|
||||
}
|
||||
|
||||
private double getIsobars() {
|
||||
switch (prediction.getType()) {
|
||||
case COSMO_EUROPE:
|
||||
return 250;
|
||||
default:
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to guess the preview format from the file name.
|
||||
*
|
||||
* @param file The file.
|
||||
* @return The preview format.
|
||||
*/
|
||||
public String guessPreviewFormat(File file) {
|
||||
if (file.getName().toLowerCase().endsWith("png")) {
|
||||
return "png";
|
||||
} else {
|
||||
return "jpeg";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a image and stores it in the destination.
|
||||
*
|
||||
* @param image The destination for the video image.
|
||||
* @param format The output format, e.g. "png" or "jpeg".
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @param hour The hour.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public void createImage(Variable variable, Time time, int hour, String format, File image) throws IOException {
|
||||
BufferedImage baseLayer = getBaseLayer(variable, time);
|
||||
BufferedImage overlayLayer = getOverlayLayer(variable, time);
|
||||
BufferedImage dataLayer = composer.createImage();
|
||||
BufferedImage frame = composer.createFrame(format.equals("png")?BufferedImage.TYPE_INT_ARGB:BufferedImage.TYPE_INT_RGB);
|
||||
if (getDataLayer(dataLayer, variable, time, hour)) {
|
||||
composer.renderImage(baseLayer, dataLayer);
|
||||
composer.renderImage(baseLayer, overlayLayer);
|
||||
composer.renderFrame(frame, baseLayer);
|
||||
ImageIO.write(frame, format, image);
|
||||
} else {
|
||||
throw new IOException("Failed to render data layer.");
|
||||
private double getIsotherms() {
|
||||
switch (prediction.getType()) {
|
||||
default:
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.dwd.VideoGenerator.IProgressMonitor;
|
||||
import com.mowesta.data.process.video.PixelFormat;
|
||||
import com.mowesta.data.process.video.VideoEncoder;
|
||||
import com.mowesta.data.process.video.VideoFrame;
|
||||
|
||||
/**
|
||||
* A video render that operates on data interpolation.
|
||||
*
|
||||
* @param <T> The state of the renderer.
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractDataVideoRenderer<T extends RendererState> extends AbstractVideoRenderer {
|
||||
|
||||
/**
|
||||
* Creates a new renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variable The variable to load.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractDataVideoRenderer(VideoGenerator generator, Variable variable, Time time) throws IOException {
|
||||
super(generator, variable, time);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderVideo(File video, int first, int last, IProgressMonitor monitor) throws IOException {
|
||||
// the frame that we need to compose and resize images
|
||||
BufferedImage frame = getComposer().createFrame(BufferedImage.TYPE_INT_ARGB);
|
||||
// the buffered for the key frame
|
||||
BufferedImage keyImage = getComposer().createImage();
|
||||
byte[] keyFrame = VideoFrame.createBuffer(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB);
|
||||
T state = createState();
|
||||
int fps = getGenerator().getFps();
|
||||
// create the encoder and interpolator
|
||||
VideoEncoder encoder = new VideoEncoder(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB, fps, getGenerator().getCrf(), getGenerator().getQuality());
|
||||
try {
|
||||
for (int i = first; i <= last; i++) {
|
||||
state.keyCount += 1;
|
||||
for (int j = 0; j < fps; j++) {
|
||||
state.interpolationCount += 1;
|
||||
state.canceled |= monitor.onFrameProcessed(state.keyCount, state.interpolationCount);
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
renderDataImage(keyImage, i, i + 1, j/(double)fps, state);
|
||||
renderFrame(frame, keyImage);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, keyFrame);
|
||||
encoder.addFrame(keyFrame);
|
||||
}
|
||||
}
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the initial rendering state.
|
||||
*
|
||||
* @return The initial rendering state.
|
||||
*/
|
||||
protected abstract T createState();
|
||||
|
||||
|
||||
/**
|
||||
* Renders The data image at the faction between start and end.
|
||||
*
|
||||
* @param image The image.
|
||||
* @param start The start time.
|
||||
* @param end The end time.
|
||||
* @param fraction The fraction between start and end.
|
||||
* @param state The rendering state.
|
||||
* @throws IOException Thrown if the image cannot be rendered.
|
||||
*/
|
||||
protected abstract void renderDataImage(BufferedImage image, int start, int end, double fraction, T state) throws IOException;
|
||||
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
T state = createState();
|
||||
renderDataImage(image, hour, hour + 1, 0, state);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator.IProgressMonitor;
|
||||
import com.mowesta.data.process.video.PixelFormat;
|
||||
import com.mowesta.data.process.video.VideoEncoder;
|
||||
import com.mowesta.data.process.video.VideoFrame;
|
||||
import com.mowesta.data.process.video.VideoInterpolator;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
|
||||
/**
|
||||
* A video renderer that uses a video interpolator to interpolate between rendered
|
||||
* data Images. This enables us to use ffmpegs interpolators such as the motion
|
||||
* interpolator which works well for moving objects such as clouds or precipitation.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractFrameVideoRenderer extends AbstractVideoRenderer {
|
||||
|
||||
/**
|
||||
* The interpolation used for this video.
|
||||
*/
|
||||
private VideoInterpolator.Type interpolation;
|
||||
|
||||
/**
|
||||
* Creates a new frame renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @param interpolation The interpolation type.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractFrameVideoRenderer(VideoGenerator generator, Variable variable, Time time, VideoInterpolator.Type interpolation) throws IOException {
|
||||
super(generator, variable, time);
|
||||
this.interpolation = interpolation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the interpolation type of the renderer.
|
||||
*
|
||||
* @return The interpolation type of the renderer.
|
||||
*/
|
||||
public VideoInterpolator.Type getInterpolation() {
|
||||
return interpolation;
|
||||
}
|
||||
|
||||
|
||||
public void renderVideo(File video, int first, int last, IProgressMonitor monitor) throws IOException {
|
||||
// the frame that we need to compose and resize images
|
||||
BufferedImage frame = getComposer().createFrame(BufferedImage.TYPE_INT_ARGB);
|
||||
// the buffered for the key frame
|
||||
BufferedImage keyImage = getComposer().createImage();
|
||||
byte[] keyFrame = VideoFrame.createBuffer(getRenderer().getWidth(), getRenderer().getHeight(), PixelFormat.ARGB);
|
||||
// the buffer for the interpolated frames
|
||||
BufferedImage interpolatedImage = getComposer().createImage();
|
||||
byte[] interpolatedFrame = VideoFrame.createBuffer(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB);
|
||||
// key frame, interpolate frame
|
||||
RendererState state = new RendererState();
|
||||
int fps = getGenerator().getFps();
|
||||
// create the encoder and interpolator
|
||||
VideoEncoder encoder = new VideoEncoder(getComposer().getWidth(), getComposer().getHeight(), PixelFormat.ARGB, fps, getGenerator().getCrf(), getGenerator().getQuality());
|
||||
try {
|
||||
VideoInterpolator interpolator = new VideoInterpolator(getRenderer().getWidth(), getRenderer().getHeight(), PixelFormat.ARGB, 1, fps + 2, interpolation);
|
||||
try {
|
||||
// create a frame callback that forwards frames from interpolator to encoder
|
||||
VideoInterpolator.FrameCallback handler = (source, pts, data) -> {
|
||||
try {
|
||||
if (state.canceled) return;
|
||||
// drop 1 frame at the beginning and one at the end for smoother motion
|
||||
int f = (int)(pts % (fps + 2));
|
||||
if (f < (fps + 1) && f > 0) {
|
||||
state.interpolationCount += 1;
|
||||
VideoFrame.decodeImage(PixelFormat.ARGB, data, interpolatedImage);
|
||||
renderFrame(frame, interpolatedImage);
|
||||
VideoFrame.encodeImage(frame, PixelFormat.ARGB, interpolatedFrame);
|
||||
encoder.addFrame(interpolatedFrame);
|
||||
state.canceled |= monitor.onFrameProcessed(state.keyCount, state.interpolationCount);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to encode image.", e);
|
||||
}
|
||||
};
|
||||
for (int i = first; i <= last; i++) {
|
||||
renderDataImage(keyImage, i);
|
||||
state.keyCount += 1;
|
||||
state.canceled |= monitor.onFrameProcessed(state.keyCount, state.interpolationCount);
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
VideoFrame.encodeImage(keyImage, PixelFormat.ARGB, keyFrame);
|
||||
interpolator.addFrame(i, keyFrame, handler);
|
||||
}
|
||||
if (state.canceled) throw new IOException("Video generation canceled.");
|
||||
VideoFrame.encodeImage(keyImage, PixelFormat.ARGB, keyFrame);
|
||||
interpolator.addFrame(last + 1, keyFrame, handler);
|
||||
interpolator.release();
|
||||
encoder.finish(video);
|
||||
} finally {
|
||||
interpolator.release();
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
encoder.finish(null);
|
||||
} catch (IOException e) { };
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.process.interpolation.LinearInterpolation;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A base class for renders that generate images from interpolated data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractLinearDataVideoRender extends AbstractDataVideoRenderer<LinearRendererState> {
|
||||
|
||||
/**
|
||||
* The interpolator.
|
||||
*/
|
||||
protected LinearInterpolation interpolation = new LinearInterpolation();
|
||||
|
||||
/**
|
||||
* Creates a new renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractLinearDataVideoRender(VideoGenerator generator, Variable variable, Time time) throws IOException {
|
||||
super(generator, variable, time);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected LinearRendererState createState() {
|
||||
return new LinearRendererState();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int start, int end, double fraction, LinearRendererState state) throws IOException {
|
||||
DoubleArray s = state.cache.get(start);
|
||||
DoubleArray e = state.cache.get(end);
|
||||
state.cache.clear();
|
||||
if (fraction == 0 || fraction == 1) {
|
||||
int h = (fraction == 0) ? start : end;
|
||||
DoubleArray a = (fraction == 0) ? s : e;
|
||||
if (a == null) a = getData(h);
|
||||
state.cache.put(h, a);
|
||||
if (state.data == null) {
|
||||
state.data = new DoubleArray(a.getSize());
|
||||
}
|
||||
for (int i = 0, sz = a.getSize(); i < sz; i++) {
|
||||
state.data.setValue(i, a.getValue(i));
|
||||
}
|
||||
} else {
|
||||
if (s == null) s = getData(start);
|
||||
state.cache.put(start, s);
|
||||
if (e == null) e = getData(end);
|
||||
state.cache.put(end, e);
|
||||
if (state.data == null) {
|
||||
state.data = new DoubleArray(s.getSize());
|
||||
}
|
||||
for (int i = 0, sz = s.getSize(); i < sz; i++) {
|
||||
state.data.setValue(i, interpolation.interpolate(s.getValue(i), e.getValue(i), fraction));
|
||||
}
|
||||
}
|
||||
renderDataImage(image, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the image from the current state.
|
||||
*
|
||||
* @param image The image.
|
||||
* @param state The state.
|
||||
* @throws IOException Thrown if the rendering fails.
|
||||
*/
|
||||
public abstract void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Loads the data for the hour.
|
||||
*
|
||||
* @param hour The hour.
|
||||
* @return The data.
|
||||
* @throws IOException Thrown if the data is not available.
|
||||
*/
|
||||
protected DoubleArray getData(int hour) throws IOException {
|
||||
File file = getPrediction().getFile(variable, time, hour);
|
||||
if (file == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
return getPrediction().getValues(file);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator.IProgressMonitor;
|
||||
|
||||
/**
|
||||
* An abstract base class for video rendering that manages details such
|
||||
* as the generation of preview frames.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public abstract class AbstractVideoRenderer {
|
||||
|
||||
/**
|
||||
* The video generator that created the renderer.
|
||||
*/
|
||||
protected VideoGenerator generator;
|
||||
/**
|
||||
* The variable that we want to render.
|
||||
*/
|
||||
protected Variable variable;
|
||||
|
||||
/**
|
||||
* The time that we render.
|
||||
*/
|
||||
protected Time time;
|
||||
|
||||
/**
|
||||
* A static image underneath the data.
|
||||
*/
|
||||
protected BufferedImage baseImage;
|
||||
|
||||
/**
|
||||
* A static image on top of the data.
|
||||
*/
|
||||
protected BufferedImage overlayImage;
|
||||
|
||||
/**
|
||||
* A temporary image to support multi-step rendering.
|
||||
*/
|
||||
protected BufferedImage tempImage;
|
||||
|
||||
/**
|
||||
* Creates a renderer for the specified variable and time.
|
||||
*
|
||||
* @param generator The video generator with the data and video settings.
|
||||
* @param variable The variable.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public AbstractVideoRenderer(VideoGenerator generator, Variable variable, Time time) throws IOException {
|
||||
this.generator = generator;
|
||||
this.variable = variable;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the video generator that created the renderer.
|
||||
*
|
||||
* @return The video generator.
|
||||
*/
|
||||
public VideoGenerator getGenerator() {
|
||||
return generator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the frame composer of the video generator.
|
||||
*
|
||||
* @return The frame composer of the video generator.
|
||||
*/
|
||||
protected VideoFrameComposer getComposer() {
|
||||
return getGenerator().getComposer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the image renderer of the video generator.
|
||||
*
|
||||
* @return The image renderer.
|
||||
*/
|
||||
protected VideoImageRenderer getRenderer() {
|
||||
return getComposer().getGenerator();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the numeric prediction of the video generator.
|
||||
*
|
||||
* @return The numeric prediction.
|
||||
*/
|
||||
protected NumericPrediction getPrediction() {
|
||||
return generator.getPrediction();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a cleared version of the temporary image.
|
||||
*
|
||||
* @return A cleared version of the temporary image.
|
||||
*/
|
||||
protected BufferedImage getTempImage() {
|
||||
if (tempImage == null) {
|
||||
tempImage = getComposer().createImage();
|
||||
}
|
||||
getComposer().clearImage(tempImage);
|
||||
return tempImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base image.
|
||||
*
|
||||
* @return The base image.
|
||||
* @throws IOException Thrown if the base image cannot be created.
|
||||
*/
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
if (baseImage == null) {
|
||||
BufferedImage temp = getTempImage();
|
||||
baseImage = getComposer().createImage();
|
||||
getRenderer().renderSoilType(baseImage, getPrediction().getValues(getPrediction().getFile(Variable.SOILTYP, time)));
|
||||
getComposer().getGenerator().renderPlantCover(temp, getPrediction().getValues(getPrediction().getFile(Variable.PLCOV, time)));
|
||||
getComposer().renderImage(baseImage, temp);
|
||||
getComposer().getGenerator().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(baseImage, temp);
|
||||
}
|
||||
return baseImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the overlay image.
|
||||
*
|
||||
* @return The overlay image.
|
||||
* @throws IOException Thrown if the overlay image cannot be created.
|
||||
*/
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
if (overlayImage == null) {
|
||||
overlayImage = getComposer().createImage();
|
||||
getRenderer().renderBoundaries(overlayImage, false);
|
||||
}
|
||||
return overlayImage;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the video from the first to the last hour.
|
||||
*
|
||||
* @param video The video.
|
||||
* @param first The first hour.
|
||||
* @param last The last hour.
|
||||
* @param monitor The progress monitor.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public abstract void renderVideo(File video, int first, int last, IProgressMonitor monitor) throws IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Renders the data image for the specified hour.
|
||||
*
|
||||
* @param image The image.
|
||||
* @param hour The hour.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected abstract void renderDataImage(BufferedImage image, int hour) throws IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Renders a preview file from the data at the specified hour.
|
||||
*
|
||||
* @param file The preview file.
|
||||
* @param hour The hour.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public void renderPreview(File file, int hour) throws IOException {
|
||||
String format = getPreviewFormat(file);
|
||||
BufferedImage output = getComposer().createFrame( format.equals("jpeg") ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
|
||||
BufferedImage data = getComposer().createImage();
|
||||
renderDataImage(data, hour);
|
||||
renderFrame(output, data);
|
||||
ImageIO.write(output, format, file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to guess the preview format from the file name.
|
||||
*
|
||||
* @param file The file.
|
||||
* @return The preview format.
|
||||
*/
|
||||
private String getPreviewFormat(File file) {
|
||||
if (file.getName().toLowerCase().endsWith("png")) {
|
||||
return "png";
|
||||
} else if (file.getName().toLowerCase().endsWith("gif")) {
|
||||
return "gif";
|
||||
} else {
|
||||
return "jpeg";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the image stack consisting of the base layer, the specified data layer and
|
||||
* the overlay layer onto the destination image.
|
||||
*
|
||||
* @param image The destination image.
|
||||
* @param dataImage The data image.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
protected void renderImage(BufferedImage image, BufferedImage dataImage) throws IOException {
|
||||
BufferedImage base = getBaseImage();
|
||||
if (base != null) getComposer().renderImage(image, base);
|
||||
getComposer().renderImage(image, dataImage);
|
||||
BufferedImage over = getOverlayImage();
|
||||
if (over != null) getComposer().renderImage(image, over);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the specified data image as a frame.
|
||||
*
|
||||
* @param frame The frame to render to.
|
||||
* @param dataImage The data image.
|
||||
* @throws IOException thrown if something fails.
|
||||
*/
|
||||
protected void renderFrame(BufferedImage frame, BufferedImage dataImage) throws IOException {
|
||||
BufferedImage temp = getTempImage();
|
||||
renderImage(temp, dataImage);
|
||||
getComposer().renderFrame(frame, temp);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.video.VideoInterpolator.Type;
|
||||
|
||||
/**
|
||||
* A video renderer for the cloud coverage that renders data images
|
||||
* from the cloud coverage and if available, cloud depth.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class CloudVideoRenderer extends AbstractFrameVideoRenderer {
|
||||
|
||||
/**
|
||||
* Creates a new video renderer for the specified time.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public CloudVideoRenderer(VideoGenerator generator, Time time) throws IOException {
|
||||
super(generator, Variable.CLCT, time, Type.MOTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
File file = getPrediction().getFile(variable, time, hour);
|
||||
if (file == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
DoubleArray data = getPrediction().getValues(file);
|
||||
file = getPrediction().getFile(Variable.CLDEPTH, time, hour);
|
||||
if (file != null) {
|
||||
getRenderer().renderCloudCoverage3D(image, data, getPrediction().getValues(file));
|
||||
} else {
|
||||
getRenderer().renderCloudCoverage(image, data);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* The renderer state of the data renderer that performs
|
||||
* a simple linear interpolation on the data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LinearRendererState extends RendererState {
|
||||
|
||||
/**
|
||||
* The loaded data hashed by hour.
|
||||
*/
|
||||
Map<Integer, DoubleArray> cache = new HashMap<>();
|
||||
|
||||
/** The double array with the interpolated data. */
|
||||
DoubleArray data;
|
||||
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.video.VideoInterpolator.Type;
|
||||
|
||||
/**
|
||||
* A video renderer for precipitation videos.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class PrecipitationVideoRenderer extends AbstractFrameVideoRenderer {
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new video renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public PrecipitationVideoRenderer(VideoGenerator generator, Time time) throws IOException {
|
||||
super(generator, Variable.PREC, time, Type.MOTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderDataImage(BufferedImage image, int hour) throws IOException {
|
||||
File f1 = getPrediction().getFile(variable, time, hour);
|
||||
File f2 = getPrediction().getFile(variable, time, hour + 1);
|
||||
if (f1 == null) throw new IOException(String.format("No file for hour %d.", hour));
|
||||
if (f2 == null) throw new IOException(String.format("No file for hour %d.", hour + 1));
|
||||
DoubleArray data = getPrediction().getValues(f2);
|
||||
DoubleArray base = getPrediction().getValues(f1);
|
||||
for (int i = 0, s = data.getSize(); i < s; i++) {
|
||||
data.setValue(i, data.getValue(i) - base.getValue(i));
|
||||
}
|
||||
getRenderer().renderPrecipitation(image, data);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.process.algorithm.GaussianBlur;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
|
||||
/**
|
||||
* A video renderer for pressure videos.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class PressureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
|
||||
/**
|
||||
* The surface height image.
|
||||
*/
|
||||
protected BufferedImage surfaceImage;
|
||||
|
||||
/**
|
||||
* The distance of the iso lines.
|
||||
*/
|
||||
protected double isoDistance;
|
||||
|
||||
/**
|
||||
* A filter to apply a Gaussian blur.
|
||||
*/
|
||||
protected GaussianBlur blur = new GaussianBlur(2);
|
||||
|
||||
/**
|
||||
* The filtered image.
|
||||
*/
|
||||
protected BufferedImage filterImage;
|
||||
|
||||
/**
|
||||
* Creates a new pressure video renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @param isoDistance The iso distance in pa (= hpa * 100).
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public PressureVideoRenderer(VideoGenerator generator, Time time, double isoDistance) throws IOException {
|
||||
super(generator, Variable.PMSL, time);
|
||||
this.isoDistance = isoDistance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a temporary image to apply the gaussian blur.
|
||||
*
|
||||
* @return The filter image.
|
||||
*/
|
||||
public BufferedImage getFilterImage() {
|
||||
if (filterImage == null) {
|
||||
filterImage = getComposer().createImage();
|
||||
}
|
||||
getComposer().clearImage(filterImage);
|
||||
return filterImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the buffered image with the surface height.
|
||||
*
|
||||
* @return The surface height image.
|
||||
* @throws IOException Thrown if the data cannot be read.
|
||||
*/
|
||||
public BufferedImage getSurfaceImage() throws IOException {
|
||||
if (surfaceImage == null) {
|
||||
surfaceImage = getComposer().createImage();
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
temp = getTempImage();
|
||||
getRenderer().renderBoundaries(temp, false);
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
}
|
||||
return surfaceImage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException {
|
||||
getRenderer().renderPressure(image, state.data);
|
||||
getComposer().renderImage(image, getSurfaceImage());
|
||||
if (isoDistance != 0) {
|
||||
// find the perimeters for the iso lines
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data);
|
||||
IntArray converted = getRenderer().getIntValues(projected, (v) -> (int)((v - 100000) / isoDistance));
|
||||
List<List<int[]>> ps = getRenderer().getPerimeters(converted);
|
||||
List<List<int[]>> result = new ArrayList<>();
|
||||
// remove the short lines
|
||||
for (List<int[]> p : ps) {
|
||||
if (p.size() > 30) result.add(p);
|
||||
}
|
||||
// render onto temp image
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderPerimeters(temp, result, 1.5f, 0xffffffff);
|
||||
// apply a blur onto the lines so they look more natural
|
||||
BufferedImage filter = getFilterImage();
|
||||
blur.apply(filter, temp);
|
||||
getComposer().renderImage(image, filter);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
// optimize performance by not rendering any base image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
// don't render any overlay image
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
/**
|
||||
* The internal state of the renderer.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class RendererState {
|
||||
/** The number of key frames generated so far. */
|
||||
int keyCount;
|
||||
/** The number of interpolated frames generated so far. */
|
||||
int interpolationCount;
|
||||
/** A flag to determine whether the process is canceled. */
|
||||
boolean canceled;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.dwd.NumericPrediction.Time;
|
||||
import com.mowesta.data.dwd.NumericPrediction.Variable;
|
||||
import com.mowesta.data.process.algorithm.GaussianBlur;
|
||||
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
import com.mowesta.data.dwd.VideoGenerator;
|
||||
|
||||
/**
|
||||
* A renderer for temperature videos.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class TemperatureVideoRenderer extends AbstractLinearDataVideoRender {
|
||||
|
||||
/**
|
||||
* The surface height image.
|
||||
*/
|
||||
protected BufferedImage surfaceImage;
|
||||
|
||||
/**
|
||||
* The image with the borders.
|
||||
*/
|
||||
protected BufferedImage borderImage;
|
||||
|
||||
/**
|
||||
* The image for the filter.
|
||||
*/
|
||||
protected BufferedImage filterImage;
|
||||
|
||||
/**
|
||||
* A filter to apply a Gaussian blur.
|
||||
*/
|
||||
protected GaussianBlur blur = new GaussianBlur(2);
|
||||
|
||||
/**
|
||||
* The distance of the isotherms in degree celsius.
|
||||
*/
|
||||
protected double isoDistance;
|
||||
|
||||
/**
|
||||
* Creates a new video renderer.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param time The time.
|
||||
* @param isoDistance The iso distance in degree centigrade, set to 0 to not draw anything.
|
||||
* @throws IOException Thrown if something fails.
|
||||
*/
|
||||
public TemperatureVideoRenderer(VideoGenerator generator, Time time, double isoDistance) throws IOException {
|
||||
super(generator, Variable.T2M, time);
|
||||
this.isoDistance = isoDistance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a temporary image to apply the gaussian blur.
|
||||
*
|
||||
* @return The filter image.
|
||||
*/
|
||||
public BufferedImage getFilterImage() {
|
||||
if (filterImage == null) {
|
||||
filterImage = getComposer().createImage();
|
||||
}
|
||||
getComposer().clearImage(filterImage);
|
||||
return filterImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the buffered image with the surface height.
|
||||
*
|
||||
* @return The surface height image.
|
||||
* @throws IOException Thrown if the data cannot be read.
|
||||
*/
|
||||
public BufferedImage getSurfaceImage() throws IOException {
|
||||
if (surfaceImage == null) {
|
||||
surfaceImage = getComposer().createImage();
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderSurfaceHeight(temp, getPrediction().getValues(getPrediction().getFile(Variable.HSURF, time)));
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
temp = getTempImage();
|
||||
getRenderer().renderBoundaries(temp, false);
|
||||
getComposer().renderImage(surfaceImage, temp);
|
||||
}
|
||||
return surfaceImage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderDataImage(BufferedImage image, LinearRendererState state) throws IOException {
|
||||
getRenderer().renderTemperature(image, state.data);
|
||||
getComposer().renderImage(image, getSurfaceImage());
|
||||
if (isoDistance != 0) {
|
||||
DoubleArray projected = getRenderer().getProjectedValues(state.data);
|
||||
IntArray converted = getRenderer().getIntValues(projected, (v) -> (int)((v - KelvinCelsiusConversion.ZERO) / isoDistance));
|
||||
List<List<int[]>> ps = getRenderer().getPerimeters(converted);
|
||||
List<List<int[]>> result = new ArrayList<>(ps.size());
|
||||
for (List<int[]> p : ps) {
|
||||
if (p.size() > 30) {
|
||||
result.add(p);
|
||||
}
|
||||
}
|
||||
// render onto temp image
|
||||
BufferedImage temp = getTempImage();
|
||||
getRenderer().renderPerimeters(temp, result, 0.25f, 0xcc444444);
|
||||
// apply a blur onto the lines so they look more natural
|
||||
BufferedImage filter = getFilterImage();
|
||||
blur.apply(filter, temp);
|
||||
getComposer().renderImage(image, filter);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BufferedImage getBaseImage() throws IOException {
|
||||
// optimize performance by not rendering any base image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected BufferedImage getOverlayImage() throws IOException {
|
||||
// don't render any overlay image
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+15
-14
@@ -1,4 +1,4 @@
|
||||
package com.mowesta.data.dwd;
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.AlphaComposite;
|
||||
import java.awt.Color;
|
||||
@@ -11,12 +11,13 @@ import com.mowesta.data.process.image.ImageRenderer.Dimension;
|
||||
import com.mowesta.data.process.image.ImageRenderer.Logo;
|
||||
|
||||
/**
|
||||
* A utility class to resize and extend the a data frame generated
|
||||
* by the frame generator.
|
||||
* A utility class to resize and extend the a data frame generated by the frame generator
|
||||
* using an optional. At the present time, this overlay is used to cover the non-existing
|
||||
* regions in the cosmo-d2 model, if we generate a 16x9 video from the data.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class FrameComposer {
|
||||
public class VideoFrameComposer {
|
||||
|
||||
/**
|
||||
* The output width.
|
||||
@@ -31,7 +32,7 @@ public class FrameComposer {
|
||||
/**
|
||||
* The frame generator.
|
||||
*/
|
||||
protected ImageGenerator generator;
|
||||
protected VideoImageRenderer renderer;
|
||||
|
||||
/**
|
||||
* The overlay to render on top of the image.
|
||||
@@ -53,25 +54,25 @@ public class FrameComposer {
|
||||
* Creates a new frame composer that rescales images to the
|
||||
* framesize.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param renderer The generator.
|
||||
* @param width The width of the output frame.
|
||||
* @param height The height of the output frame.
|
||||
*/
|
||||
public FrameComposer(ImageGenerator generator, int width, int height) {
|
||||
this(generator, null, width, height);
|
||||
public VideoFrameComposer(VideoImageRenderer renderer, int width, int height) {
|
||||
this(renderer, null, width, height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new frame composer rescales images to the framesize
|
||||
* and adds the specified overlay image.
|
||||
*
|
||||
* @param generator The generator.
|
||||
* @param renderer The generator.
|
||||
* @param overlay The overlay to render on top of a frame.
|
||||
* @param width The width of the output frame.
|
||||
* @param height The height of the output frame.
|
||||
*/
|
||||
public FrameComposer(ImageGenerator generator, BufferedImage overlay, int width, int height) {
|
||||
this.generator = generator;
|
||||
public VideoFrameComposer(VideoImageRenderer renderer, BufferedImage overlay, int width, int height) {
|
||||
this.renderer = renderer;
|
||||
this.overlay = overlay;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
@@ -100,8 +101,8 @@ public class FrameComposer {
|
||||
*
|
||||
* @return The frame generator.
|
||||
*/
|
||||
public ImageGenerator getGenerator() {
|
||||
return generator;
|
||||
public VideoImageRenderer getGenerator() {
|
||||
return renderer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,7 +159,7 @@ public class FrameComposer {
|
||||
* @return The image for the image generator.
|
||||
*/
|
||||
public BufferedImage createImage() {
|
||||
return new BufferedImage(generator.getWidth(), generator.getHeight(), BufferedImage.TYPE_INT_ARGB);
|
||||
return new BufferedImage(renderer.getWidth(), renderer.getHeight(), BufferedImage.TYPE_INT_ARGB);
|
||||
}
|
||||
|
||||
/**
|
||||
+144
-48
@@ -1,10 +1,15 @@
|
||||
package com.mowesta.data.dwd;
|
||||
package com.mowesta.data.dwd.render;
|
||||
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.algorithm.MarchingSquares;
|
||||
import com.mowesta.data.process.color.CloudDepthColorScheme;
|
||||
import com.mowesta.data.process.color.IColorScheme;
|
||||
import com.mowesta.data.process.color.PlantCoverColorScheme;
|
||||
@@ -19,18 +24,38 @@ import com.mowesta.data.process.image.BoundaryRenderer;
|
||||
import com.mowesta.data.process.image.DataRenderer;
|
||||
import com.mowesta.data.process.image.ImageFiller;
|
||||
import com.mowesta.data.process.projection.IProjection;
|
||||
import com.mowesta.data.process.projection.ImageProjection;
|
||||
import com.mowesta.data.process.source.DoubleArraySource;
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
|
||||
/**
|
||||
* A utility class to render videos from dwd data. This class is responsible for
|
||||
* rendering the data at a (nearly) native resolution resulting from the
|
||||
* contents of the grib files. The rescaling of images is done using regular
|
||||
* image functions in the frame composer.
|
||||
* A utility class to render videos from DWD data. This class is responsible for rendering the data at a
|
||||
* (nearly) native resolution resulting from the contents of the grib files. The rescaling of images is
|
||||
* done using regular image functions in the frame composer. This way, we do not have to handle the
|
||||
* scaling of data at the rendering level. The drawback is an increased rendering time, however, cropping
|
||||
* can be done by adjusting the projection.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ImageGenerator {
|
||||
public class VideoImageRenderer {
|
||||
|
||||
/**
|
||||
* An interface used to convert a double value to
|
||||
* an integer.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface IntConverter {
|
||||
/**
|
||||
* Returns the integer after conversion.
|
||||
*
|
||||
* @param value The value.
|
||||
* @return The integer.
|
||||
*/
|
||||
int convert(double value);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The latitude values.
|
||||
@@ -41,7 +66,11 @@ public class ImageGenerator {
|
||||
*/
|
||||
protected DoubleArray longitudes;
|
||||
/**
|
||||
* The projection to use.
|
||||
* The precomputed projection to use.
|
||||
*/
|
||||
protected ImageProjection imageProjection;
|
||||
/**
|
||||
* The projection.
|
||||
*/
|
||||
protected IProjection projection;
|
||||
/**
|
||||
@@ -71,12 +100,13 @@ public class ImageGenerator {
|
||||
* @param width The image width.
|
||||
* @param height The image height.
|
||||
*/
|
||||
public ImageGenerator(DoubleArray longitudes, DoubleArray latitudes, IProjection projection, int width, int height) {
|
||||
public VideoImageRenderer(DoubleArray longitudes, DoubleArray latitudes, IProjection projection, int width, int height) {
|
||||
this.projection = projection;
|
||||
this.longitudes = longitudes;
|
||||
this.latitudes = latitudes;
|
||||
this.projection = projection;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.imageProjection = new ImageProjection(projection, longitudes, latitudes, width, height);
|
||||
this.imageFiller = new ImageFiller(longitudes, latitudes, projection, width, height);
|
||||
}
|
||||
|
||||
@@ -126,32 +156,87 @@ public class ImageGenerator {
|
||||
* @param pmsl The pressure levels.
|
||||
*/
|
||||
public void renderPressure(BufferedImage image, DoubleArray pmsl) {
|
||||
double min = 0, max = 0, avg = 0;
|
||||
boolean first = true;
|
||||
int s = Math.min(longitudes.getSize(), Math.min(latitudes.getSize(), pmsl.getSize()));
|
||||
for (int i = 0; i < s; i++) {
|
||||
double longitude = longitudes.getValue(i);
|
||||
double latitude = latitudes.getValue(i);
|
||||
double value = pmsl.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
if (first) {
|
||||
min = value;
|
||||
max = value;
|
||||
first = false;
|
||||
} else {
|
||||
min = Math.min(min, value);
|
||||
max = Math.max(max, value);
|
||||
}
|
||||
}
|
||||
avg += value;
|
||||
}
|
||||
avg /= s;
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new PressureColorScheme(avg, min, max));
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PressureColorScheme(101325, 99825, 102825));
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, pmsl), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the perimeters onto the image.
|
||||
*
|
||||
* @param image The image.
|
||||
* @param perimeters The perimeters.
|
||||
* @param swidth The width to render the outlines.
|
||||
* @param color The color to render with.
|
||||
*/
|
||||
public void renderPerimeters(BufferedImage image, List<List<int[]>> perimeters, float swidth, int color) {
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setColor(new Color(color, true));
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setStroke(new BasicStroke(swidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
|
||||
int offset = (int)Math.ceil(swidth);
|
||||
for (List<int[]> perimeter: perimeters) {
|
||||
int[] x = new int[perimeter.size()];
|
||||
int[] y = new int[perimeter.size()];
|
||||
for (int i = 0; i < perimeter.size(); i++) {
|
||||
x[i] = perimeter.get(i)[0];
|
||||
if (x[i] == 0) x[i] = -offset;
|
||||
if (x[i] == this.width - 1) x[i] = this.width + offset - 1;
|
||||
y[i] = perimeter.get(i)[1];
|
||||
if (y[i] == 0) y[i] = -offset;
|
||||
if (y[i] == height - 1) y[i] = this.height + offset - 1;
|
||||
}
|
||||
g.drawPolyline(x, y, x.length);
|
||||
}
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the perimeters in the picture.
|
||||
*
|
||||
* @param values The values of the picture.
|
||||
* @return The perimeters found in the picture.
|
||||
*/
|
||||
public List<List<int[]>> getPerimeters(IntArray values) {
|
||||
IntArray found = new IntArray(width * height);
|
||||
List<List<int[]>> perimeters = new ArrayList<>();
|
||||
for (int x = 1; x < width - 1; x++) {
|
||||
for (int y = 1; y < height - 1; y++) {
|
||||
if (found.getValue(y * width + x) != 0)
|
||||
continue;
|
||||
int cmp = values.getValue(y * width + x);
|
||||
i: for (int i = -1; i <= 1; i++) {
|
||||
for (int j = -1; j <= 1; j++) {
|
||||
int nx = Math.min(width - 1, Math.max(0, x + i));
|
||||
int ny = Math.min(height - 1, Math.max(0, y + j));
|
||||
if (cmp > values.getValue(ny * width + nx)) {
|
||||
MarchingSquares algo = new MarchingSquares(width, height, (a, b) -> {
|
||||
return values.getValue(b * width + a) == cmp;
|
||||
});
|
||||
List<int[]> perimeter = algo.findPerimenter(x, y);
|
||||
for (int[] v: perimeter) {
|
||||
try {
|
||||
found.setValue(v[1] * width + v[0], 1);
|
||||
} catch (ArrayIndexOutOfBoundsException e) {
|
||||
System.out.println(v[1] + " " + v[0] + " " + width + " " + height);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
perimeters.add(perimeter);
|
||||
break i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return perimeters;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Renders an image from the soil type.
|
||||
*
|
||||
@@ -160,7 +245,7 @@ public class ImageGenerator {
|
||||
*/
|
||||
public void renderSoilType(BufferedImage image, DoubleArray soilType) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new SoilTypeColorScheme());
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new SoilTypeColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, soilType), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
@@ -173,7 +258,7 @@ public class ImageGenerator {
|
||||
*/
|
||||
public void renderTemperature(BufferedImage image, DoubleArray t2m) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new ScientificTemperatureColorScheme(), Collections.singletonList(new KelvinCelsiusConversion()));
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new ScientificTemperatureColorScheme(), Collections.singletonList(new KelvinCelsiusConversion()));
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, t2m), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
@@ -187,7 +272,7 @@ public class ImageGenerator {
|
||||
*/
|
||||
public void renderPrecipitation(BufferedImage image, DoubleArray prec) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new PrecipitationColorScheme());
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PrecipitationColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, prec), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
@@ -201,7 +286,7 @@ public class ImageGenerator {
|
||||
*/
|
||||
public void renderPlantCover(BufferedImage image, DoubleArray plcov) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new PlantCoverColorScheme());
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new PlantCoverColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, plcov), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
@@ -241,20 +326,35 @@ public class ImageGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the projected values and transforms them into an integer.
|
||||
*
|
||||
* @param base The base values.
|
||||
* @param converter The converter.
|
||||
* @return The converted values.
|
||||
*/
|
||||
public IntArray getIntValues(DoubleArray base, IntConverter converter) {
|
||||
IntArray projected = new IntArray(base.getSize());
|
||||
for (int i = 0, s = base.getSize(); i < s; i++) {
|
||||
projected.setValue(i, converter.convert(base.getValue(i)));
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the projected values.
|
||||
*
|
||||
* @param base The base.
|
||||
* @return The projected values.
|
||||
*/
|
||||
protected DoubleArray getProjectedValues(DoubleArray base) {
|
||||
public DoubleArray getProjectedValues(DoubleArray base) {
|
||||
DoubleArray projected = new DoubleArray(width * height);
|
||||
for (int i = 0, s = Math.min(longitudes.getSize(), Math.min(latitudes.getSize(), base.getSize())); i < s; i++) {
|
||||
double longitude = longitudes.getValue(i);
|
||||
double latitude = latitudes.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
int x = Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width)));
|
||||
int y = Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height)));
|
||||
if (imageProjection.isVisible(i)) {
|
||||
int x = imageProjection.getX(i);
|
||||
int y = imageProjection.getY(i);
|
||||
projected.setValue(y * width + x, base.getValue(i));
|
||||
}
|
||||
}
|
||||
@@ -270,7 +370,7 @@ public class ImageGenerator {
|
||||
*/
|
||||
public void renderCloudCoverage(BufferedImage image, DoubleArray clcm) {
|
||||
clearImage(image);
|
||||
DataRenderer renderer = new DataRenderer(projection, new WhiteCloudColorScheme());
|
||||
DataRenderer renderer = new DataRenderer(imageProjection, new WhiteCloudColorScheme());
|
||||
renderer.renderData(new DoubleArraySource(longitudes, latitudes, clcm), image);
|
||||
imageFiller.apply(image);
|
||||
}
|
||||
@@ -286,16 +386,12 @@ public class ImageGenerator {
|
||||
clearImage(image);
|
||||
IColorScheme cloudScheme = new WhiteCloudColorScheme();
|
||||
IColorScheme depthScheme = new CloudDepthColorScheme();
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
int s = Math.min(longitudes.getSize(), latitudes.getSize());
|
||||
s = Math.min(cldepth.getSize(), Math.min(clct.getSize(), s));
|
||||
for (int i = 0; i < s; i++) {
|
||||
double latitude = latitudes.getValue(i);
|
||||
double longitude = longitudes.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
int px = Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width)));
|
||||
int py = Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height)));
|
||||
if (imageProjection.isVisible(i)) {
|
||||
int px = imageProjection.getX(i);
|
||||
int py = imageProjection.getY(i);
|
||||
int depth = depthScheme.getColor(cldepth.getValue(i));
|
||||
int cover = cloudScheme.getColor(clct.getValue(i));
|
||||
image.setRGB(px, py, (cover & 0xFF000000) | (depth & 0x00FFFFFF));
|
||||
@@ -28,7 +28,19 @@ public class NominatimCity extends NominatimObject {
|
||||
* The country that contains this city.
|
||||
*/
|
||||
private long country;
|
||||
|
||||
|
||||
/**
|
||||
* This string contains the is_in relation used to disambiguate
|
||||
* cities during the import.
|
||||
*/
|
||||
private String inside;
|
||||
|
||||
/**
|
||||
* This string is the first name of a parent used to disambiguate
|
||||
* cities during import.
|
||||
*/
|
||||
private String parent;
|
||||
|
||||
/**
|
||||
* Returns the capital.
|
||||
*
|
||||
@@ -101,4 +113,42 @@ public class NominatimCity extends NominatimObject {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the parent.
|
||||
*
|
||||
* @return The parent.
|
||||
*/
|
||||
public String getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the parent.
|
||||
*
|
||||
* @param parent The parent to set.
|
||||
*/
|
||||
public void setParent(String parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the inside.
|
||||
*
|
||||
* @return The inside.
|
||||
*/
|
||||
public String getInside() {
|
||||
return inside;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the inside.
|
||||
*
|
||||
* @param inside The inside to set.
|
||||
*/
|
||||
public void setInside(String inside) {
|
||||
this.inside = inside;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An implementation of the Douglas Peucker polyline simplification algorithm.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DouglasPeucker {
|
||||
|
||||
/**
|
||||
* An interface for a distance metric.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface Metric {
|
||||
|
||||
/**
|
||||
* Computes the distance between two points.
|
||||
*
|
||||
* @param a The first point.
|
||||
* @param b The second point.
|
||||
* @return The distance.
|
||||
*/
|
||||
double getDistance(double[] a, int[] b);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The distance threshold used during simplification.
|
||||
*/
|
||||
private double distance;
|
||||
|
||||
/**
|
||||
* The metric.
|
||||
*/
|
||||
private Metric metric;
|
||||
|
||||
/**
|
||||
* Creates a new algorithm using the specified distance threshold
|
||||
* and a Euclidean distance metric.
|
||||
*
|
||||
* @param distance The threshold distance.
|
||||
*/
|
||||
public DouglasPeucker(double distance) {
|
||||
this((a, b) -> Math.sqrt(Math.pow(a[0] - b[0] ,2) + Math.pow(a [1] - b[1], 2)), distance);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new algorithm using the specified distance threshold
|
||||
* and the specified distance metric.
|
||||
*
|
||||
* @param metric The distance metric.
|
||||
* @param distance The distance threshold..
|
||||
*/
|
||||
public DouglasPeucker(Metric metric, double distance) {
|
||||
this.metric = metric;
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the distance threshold for simplification.
|
||||
*
|
||||
* @return The distance threshold
|
||||
*/
|
||||
public double getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the distance threshold for simplification.
|
||||
*
|
||||
* @param distance The distance to set.
|
||||
*/
|
||||
public void setDistance(double distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplifies a polyline by removing points. The resulting line will not deviate
|
||||
* more than the specified distance as defined by the specified metric.
|
||||
* The algorithm implemented here is the so-called Douglas-Peucker algorithm.
|
||||
*
|
||||
* @param polyline The polyline to simplify.
|
||||
* @return The list with the simplified coordinates.
|
||||
*/
|
||||
public List<int[]> simplify(List<int[]> polyline) {
|
||||
List<int[]> input = new ArrayList<>(polyline);
|
||||
if (input.size() > 2 && metric != null) {
|
||||
List<int[]> result = new ArrayList<>();
|
||||
List<List<int[]>> backlog = new ArrayList<>();
|
||||
backlog.add(input);
|
||||
while (!backlog.isEmpty()) {
|
||||
List<int[]> next = backlog.remove(0);
|
||||
double dmax = 0;
|
||||
int split = -1;
|
||||
for (int i = 1; i < next.size() - 1; i++) {
|
||||
int[] p = next.get(i);
|
||||
double[] c = getClosestPointOnSlope(next.get(0), next.get(next.size() - 1), p);
|
||||
if (c == null) {
|
||||
// special case that the first and last point are identical
|
||||
int[] n = next.get(0);
|
||||
c = new double[] { n[0], n[1] };
|
||||
}
|
||||
double d = metric.getDistance(c, p);
|
||||
if (d > dmax || split == -1) {
|
||||
dmax = d;
|
||||
split = i;
|
||||
}
|
||||
}
|
||||
if (split != -1 && dmax > distance) {
|
||||
List<int[]> first = new ArrayList<>();
|
||||
for (int i = 0; i <= split; i++) {
|
||||
first.add(next.get(i));
|
||||
}
|
||||
List<int[]> second = new ArrayList<>();
|
||||
for (int i = split; i < next.size(); i++) {
|
||||
second.add(next.get(i));
|
||||
}
|
||||
// add the last element twice, again
|
||||
backlog.add(0, second);
|
||||
backlog.add(0, first);
|
||||
} else {
|
||||
result.add(next.get(0));
|
||||
result.add(next.get(next.size() - 1));
|
||||
}
|
||||
}
|
||||
// it is possible that the list will contain duplicates due to
|
||||
// the removal, so lets remove the ones which are really close
|
||||
return deduplicate(result);
|
||||
} else {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes duplicate adjacent coordinates form the polyline. Identical
|
||||
* coordinates are identified by the epsilon.
|
||||
*
|
||||
* @param polyline The polyline.
|
||||
* @return The deduplicated polyline.
|
||||
*/
|
||||
public List<int[]> deduplicate(List<int[]> polyline) {
|
||||
List<int[]> result = new ArrayList<>();
|
||||
if (!polyline.isEmpty()) {
|
||||
result.add(polyline.get(0));
|
||||
for (int i = 1; i < polyline.size(); i++) {
|
||||
int[] prev = result.get(result.size() - 1);
|
||||
int[] next = polyline.get(i);
|
||||
if (prev[0] != next[0] || prev[1] != next[1]) {
|
||||
result.add(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Computes the closest point on a linear slope that is defined
|
||||
* by two points.
|
||||
*
|
||||
* @param line1
|
||||
* The first coordinate of the linear slope.
|
||||
* @param line2
|
||||
* The second coordinate of the linear slope.
|
||||
* @param point
|
||||
* The point to start from.
|
||||
* @return The point that is closest on the linear slope or null
|
||||
* if line1 and line2 are not spanning a linear slope.
|
||||
*/
|
||||
private double[] getClosestPointOnSlope(int[] line1, int[] line2, int[] point) {
|
||||
double line1x = line1[0];
|
||||
double line1y = line1[1];
|
||||
double apx = point[0] - line1x;
|
||||
double apy = point[1] - line1y;
|
||||
double abx = line2[0] - line1x;
|
||||
double aby = line2[1] - line1y;
|
||||
double ab2 = abx * abx + aby * aby;
|
||||
double ap_ab = apx * abx + apy * aby;
|
||||
double t = ap_ab / ab2;
|
||||
if (Double.isInfinite(t) || Double.isNaN(t)) {
|
||||
return null;
|
||||
}
|
||||
return new double[] { line1x + abx * t, line1y + aby * t };
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.ConvolveOp;
|
||||
import java.awt.image.Kernel;
|
||||
|
||||
/**
|
||||
* A class to apply a Gaussian blur filter.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class GaussianBlur {
|
||||
|
||||
/**
|
||||
* The radius.
|
||||
*/
|
||||
private int radius;
|
||||
|
||||
private ConvolveOp horizontal;
|
||||
|
||||
private ConvolveOp vertical;
|
||||
|
||||
/**
|
||||
* Creates a new gaussian blur filter
|
||||
* using the specified radius.
|
||||
*
|
||||
* @param radius The radius.;
|
||||
*/
|
||||
public GaussianBlur(int radius) {
|
||||
if (radius < 1) throw new IllegalArgumentException("Invalid radius.");
|
||||
this.radius = radius;
|
||||
float[] data = getCoefficients(radius);
|
||||
horizontal = new ConvolveOp(new Kernel(data.length, 1, data), ConvolveOp.EDGE_NO_OP, null);
|
||||
vertical = new ConvolveOp(new Kernel(1, data.length, data), ConvolveOp.EDGE_NO_OP, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the radius.
|
||||
*
|
||||
* @return The radius.
|
||||
*/
|
||||
public int getRadius() {
|
||||
return radius;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Applies the filter to the image.
|
||||
*
|
||||
* @param result The result.
|
||||
* @param image The image.
|
||||
*/
|
||||
public void apply(BufferedImage result, BufferedImage image) {
|
||||
vertical.filter(horizontal.filter(image, null), result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the coefficients for the blur with the specified radius.
|
||||
*
|
||||
* @param radius The radius.
|
||||
* @return The coefficients.
|
||||
*/
|
||||
private float[] getCoefficients(int radius) {
|
||||
if (radius < 1) throw new IllegalArgumentException("Invalid radius.");
|
||||
int size = radius * 2 + 1;
|
||||
float[] data = new float[size];
|
||||
|
||||
float sigma = radius / 3.0f;
|
||||
float twoSigmaSquare = 2.0f * sigma * sigma;
|
||||
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
|
||||
float total = 0.0f;
|
||||
|
||||
for (int i = -radius; i <= radius; i++) {
|
||||
float distance = i * i;
|
||||
int index = i + radius;
|
||||
data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
|
||||
total += data[index];
|
||||
}
|
||||
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
data[i] /= total;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An implementation of a marching square algorithm mostly stolen from
|
||||
* Phill Spiess development blog. This implementation is modified
|
||||
* to walk off the image by 1 pixel such that the polygons are not
|
||||
* cut off directly at the border which would result in many white
|
||||
* border pixels.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MarchingSquares {
|
||||
|
||||
/**
|
||||
* A raster to search through.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface Raster {
|
||||
|
||||
/**
|
||||
* Determines whether the point in the raster
|
||||
* is inside or outside of the area whose
|
||||
* perimeter shall be found.
|
||||
*
|
||||
* @param x The x coordinate.
|
||||
* @param y The y coordinate.
|
||||
* @return True if x and y are part of the area.
|
||||
*/
|
||||
boolean isArea(int x, int y);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The width of the raster.
|
||||
*/
|
||||
private int width;
|
||||
|
||||
/**
|
||||
* The height of the raster.
|
||||
*/
|
||||
private int height;
|
||||
|
||||
/**
|
||||
* The raster to search through.
|
||||
*/
|
||||
private Raster raster;
|
||||
|
||||
/**
|
||||
* Creates a new marching squares algorithm.
|
||||
*
|
||||
* @param width The width of the image.
|
||||
* @param height The height of the image.
|
||||
* @param data The raster data.
|
||||
*/
|
||||
public MarchingSquares(int width, int height, Raster data) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.raster = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a starting point if there is one.
|
||||
*
|
||||
* @return The starting point [x, y] or null.
|
||||
*/
|
||||
public int[] findStart() {
|
||||
for (int i = 0; i < height; i++) {
|
||||
for (int j = 0; j < width; j++) {
|
||||
if (isArea(j, i)) {
|
||||
return new int[] { j, i };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes an int that encodes the
|
||||
* fill state of 4 pixels.
|
||||
*
|
||||
* @param x The x coordinate.
|
||||
* @param y The y coordinate.
|
||||
* @return The encoded state.
|
||||
*/
|
||||
private int getState(int x, int y) {
|
||||
int state = 0;
|
||||
if (isArea(x - 1, y - 1))
|
||||
state |= 1;
|
||||
if (isArea(x, y - 1))
|
||||
state |= 2;
|
||||
if (isArea(x - 1, y))
|
||||
state |= 4;
|
||||
if (isArea(x, y))
|
||||
state |= 8;
|
||||
return state;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines the direction for the next step based on
|
||||
* the state of the area around the pixel. The previous
|
||||
* step direction is used for disambiguation.
|
||||
*
|
||||
* @param x The x coordinate.
|
||||
* @param y The y coordinate.
|
||||
* @param previous The previous step.
|
||||
* @return The next direction.
|
||||
*/
|
||||
private Direction getDirection(int x, int y, Direction previous) {
|
||||
// compute the state based on the fill of 4 points
|
||||
switch (getState(x, y)) {
|
||||
case 1:
|
||||
return Direction.UP;
|
||||
case 2:
|
||||
return Direction.RIGHT;
|
||||
case 3:
|
||||
return Direction.RIGHT;
|
||||
case 4:
|
||||
return Direction.LEFT;
|
||||
case 5:
|
||||
return Direction.UP;
|
||||
case 6:
|
||||
if (previous == Direction.UP)
|
||||
return Direction.LEFT;
|
||||
else
|
||||
return Direction.RIGHT;
|
||||
case 7:
|
||||
return Direction.RIGHT;
|
||||
case 8:
|
||||
return Direction.DOWN;
|
||||
case 9:
|
||||
if (previous == Direction.RIGHT)
|
||||
return Direction.UP;
|
||||
else
|
||||
return Direction.DOWN;
|
||||
case 10:
|
||||
return Direction.DOWN;
|
||||
case 11:
|
||||
return Direction.DOWN;
|
||||
case 12:
|
||||
return Direction.LEFT;
|
||||
case 13:
|
||||
return Direction.UP;
|
||||
case 14:
|
||||
return Direction.LEFT;
|
||||
default:
|
||||
return Direction.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the value at x and y is part of the target area. Pixels
|
||||
* outside the image are considered to be not part of the area to avoid walking
|
||||
* outside of the image.
|
||||
*
|
||||
* @param x
|
||||
* The x coordinate.
|
||||
* @param y
|
||||
* The y coordinate.
|
||||
* @return True if the coordinate
|
||||
*/
|
||||
private boolean isArea(int x, int y) {
|
||||
if (x < 0 || y < 0 || x >= width || y >= height) {
|
||||
return false;
|
||||
} else {
|
||||
return raster.isArea(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the perimeter of the area starting at x and y. Note that the input x
|
||||
* and y must already lie on the perimeter for this method to function properly.
|
||||
*
|
||||
* @param startX
|
||||
* The x coordinate.
|
||||
* @param startY
|
||||
* The y coordinate.
|
||||
* @return The list of coordinates on the perimeter.
|
||||
*/
|
||||
public List<int[]> findPerimenter(int startX, int startY) {
|
||||
// sanity checking
|
||||
startX = Math.max(0, Math.min(width - 1, startX));
|
||||
startY = Math.max(0, Math.min(height - 1, startY));
|
||||
// result list
|
||||
List<int[]> result = new ArrayList<int[]>();
|
||||
// current point
|
||||
int x = startX;
|
||||
int y = startY;
|
||||
Direction previous = Direction.NONE;
|
||||
Direction current = Direction.NONE;
|
||||
do {
|
||||
// Evaluate our state, and set up our next direction
|
||||
current = getDirection(x, y, previous);
|
||||
// If our current point is within our image
|
||||
// add it to the list of points
|
||||
result.add(new int[] { Math.max(0, Math.min(width - 1, x)), Math.max(0, Math.min(height - 1, y)) });
|
||||
switch (current) {
|
||||
case UP:
|
||||
y--;
|
||||
break;
|
||||
case LEFT:
|
||||
x--;
|
||||
break;
|
||||
case DOWN:
|
||||
y++;
|
||||
break;
|
||||
case RIGHT:
|
||||
x++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
previous = current;
|
||||
} while (x != startX || y != startY);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The direction to follow the perimeter.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
private enum Direction {
|
||||
NONE, UP, DOWN, LEFT, RIGHT
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.mowesta.data.process.algorithm;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
|
||||
/**
|
||||
* A class to apply morphological operations on rectangular masks.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Morphology {
|
||||
|
||||
/**
|
||||
* An interface for operators.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public interface Operator {
|
||||
/**
|
||||
* Applies the operator to to the value.
|
||||
*
|
||||
* @param value The value.
|
||||
* @param previous The previous value.
|
||||
* @return The result of the operation.
|
||||
*/
|
||||
double apply(double value, Double previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* An operator to apply erosion.
|
||||
*/
|
||||
public static final Operator ERODE = (v, p) -> { if (p == null) return v; else return Math.min(v, p); };
|
||||
|
||||
/**
|
||||
* An operator to apply dilation.
|
||||
*/
|
||||
public static final Operator DILATE = (v, p) -> { if (p == null) return v; else return Math.max(v, p); };
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*/
|
||||
private int width;
|
||||
/**
|
||||
* The height of the image.
|
||||
*/
|
||||
private int height;
|
||||
/**
|
||||
* The size of the mask in pixels.
|
||||
*/
|
||||
private int size;
|
||||
|
||||
/**
|
||||
* Creates a new class to run morphological operations on the
|
||||
* image with the specified dimensions using a mask of the specified size.
|
||||
*
|
||||
* @param width The width.
|
||||
* @param height The height.
|
||||
* @param size The size.
|
||||
*/
|
||||
public Morphology(int width, int height, int size) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.size = Math.abs(size);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Applies the operator to the values inside the result.
|
||||
*
|
||||
* @param result The result.
|
||||
* @param values The values.
|
||||
* @param operator The operator.
|
||||
*/
|
||||
public void apply(DoubleArray result, DoubleArray values, Operator operator) {
|
||||
for (int i = size, ws = width - size; i < ws; i++) {
|
||||
for (int j = size, hs = height - size; j < hs; j++) {
|
||||
Double current = null;
|
||||
for (int k = -size; k <= size; k++) {
|
||||
for (int l = -size; l <= size; l++) {
|
||||
int x = (i + k);
|
||||
int y = (j + l);
|
||||
current = operator.apply(values.getValue(y * width + x), current);
|
||||
}
|
||||
}
|
||||
result.setValue(j * width + i, current);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the local minima in the values.
|
||||
*
|
||||
* @param values The values.
|
||||
* @return The local minima.
|
||||
*/
|
||||
public List<int[]> getMinima(DoubleArray values) {
|
||||
|
||||
List<int[]> results = new ArrayList<>();
|
||||
for (int i = size, ws = width - size; i < ws; i++) {
|
||||
j: for (int j = size, hs = height - size; j < hs; j++) {
|
||||
double current = values.getValue(j * width + i);
|
||||
for (int k = -size; k <= size; k++) {
|
||||
for (int l = -size; l <= size; l++) {
|
||||
double v = values.getValue((j + l) * width + (i + k));
|
||||
if (v < current) continue j;
|
||||
}
|
||||
}
|
||||
results.add(new int[] { i, j });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the local maxima in the values.
|
||||
*
|
||||
* @param values The values.
|
||||
* @return The local maxima.
|
||||
*/
|
||||
public List<int[]> getMaxima(DoubleArray values) {
|
||||
List<int[]> results = new ArrayList<>();
|
||||
for (int i = size, ws = width - size; i < ws; i++) {
|
||||
j: for (int j = size, hs = height - size; j < hs; j++) {
|
||||
double current = values.getValue(j * width + i);
|
||||
for (int k = -size; k <= size; k++) {
|
||||
for (int l = -size; l <= size; l++) {
|
||||
double v = values.getValue((j + l) * width + (i + k));
|
||||
if (v > current) continue j;
|
||||
}
|
||||
}
|
||||
results.add(new int[] { i, j });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ public class KelvinCelsiusConversion implements IDataConversion {
|
||||
/**
|
||||
* The constant to convert Kelvin to degree's Celsius.
|
||||
*/
|
||||
private static final double ZERO = -273.15;
|
||||
public static final double ZERO = -273.15;
|
||||
|
||||
|
||||
@Override
|
||||
|
||||
@@ -61,6 +61,7 @@ public class ColorScaleRenderer {
|
||||
* Creates a new color scale renderer.
|
||||
*
|
||||
* @param colorScheme The scheme to render.
|
||||
* @param provider A label provider.
|
||||
*/
|
||||
public ColorScaleRenderer(IColorScheme colorScheme, LabelProvider provider) {
|
||||
this.colorScheme = colorScheme;
|
||||
|
||||
@@ -6,7 +6,7 @@ import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.color.IColorScheme;
|
||||
import com.mowesta.data.process.conversion.IDataConversion;
|
||||
import com.mowesta.data.process.projection.IProjection;
|
||||
import com.mowesta.data.process.projection.ImageProjection;
|
||||
import com.mowesta.data.process.source.IDataSource;
|
||||
|
||||
/**
|
||||
@@ -15,15 +15,17 @@ import com.mowesta.data.process.source.IDataSource;
|
||||
* @author Marcus
|
||||
*/
|
||||
public class DataRenderer {
|
||||
|
||||
|
||||
/**
|
||||
* The projection to convert wgs84 into image coordinates.
|
||||
* The image projection to speed up the projection process.
|
||||
*/
|
||||
protected IProjection projection;
|
||||
protected ImageProjection projection;
|
||||
|
||||
/**
|
||||
* The color scheme to apply to the pixels based on the values.
|
||||
*/
|
||||
protected IColorScheme scheme;
|
||||
|
||||
/**
|
||||
* An optional list of data conversions.
|
||||
*/
|
||||
@@ -36,7 +38,7 @@ public class DataRenderer {
|
||||
* @param projection The projection to convert wgs84 into image coordinates.
|
||||
* @param scheme The color scheme to apply to the pixels based on the values.
|
||||
*/
|
||||
public DataRenderer(IProjection projection, IColorScheme scheme) {
|
||||
public DataRenderer(ImageProjection projection, IColorScheme scheme) {
|
||||
this(projection, scheme, Collections.emptyList());
|
||||
}
|
||||
|
||||
@@ -50,7 +52,7 @@ public class DataRenderer {
|
||||
* each data value before passing it to the color scheme in the order in which
|
||||
* it appears in the list.
|
||||
*/
|
||||
public DataRenderer(IProjection projection, IColorScheme scheme, List<IDataConversion> conversions) {
|
||||
public DataRenderer(ImageProjection projection, IColorScheme scheme, List<IDataConversion> conversions) {
|
||||
this.projection = projection;
|
||||
this.scheme = scheme;
|
||||
this.conversions = conversions;
|
||||
@@ -63,21 +65,19 @@ public class DataRenderer {
|
||||
* @param image The image to render to.
|
||||
*/
|
||||
public void renderData(IDataSource source, BufferedImage image) {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
int index = 0;
|
||||
while (source.moveNext()) {
|
||||
double latitude = source.getLatitude();
|
||||
double longitude = source.getLongitude();
|
||||
double value = source.getValue();
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
int px = Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width)));
|
||||
int py = Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height)));
|
||||
if (projection.isVisible(index)) {
|
||||
int px = projection.getX(index);
|
||||
int py = projection.getY(index);
|
||||
double value = source.getValue();
|
||||
for (int i = 0; i < conversions.size(); i++) {
|
||||
value = conversions.get(i).convert(value);
|
||||
}
|
||||
int color = scheme.getColor(value);
|
||||
image.setRGB(px, py, color);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.mowesta.data.process.projection;
|
||||
|
||||
import com.mowesta.data.process.util.DoubleArray;
|
||||
import com.mowesta.data.process.util.IntArray;
|
||||
|
||||
/**
|
||||
* A projection that is pre-computed to ensure that the angle functions are
|
||||
* not repeatedly called during the video generation process.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ImageProjection {
|
||||
|
||||
/**
|
||||
* The projected x-coordinate of the associated wgs coordinate.
|
||||
*/
|
||||
private IntArray x;
|
||||
|
||||
/**
|
||||
* The projected y-coordinate of the associated wgs coordinate.
|
||||
*/
|
||||
private IntArray y;
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*/
|
||||
private int width;
|
||||
|
||||
/**
|
||||
* The height of the image.
|
||||
*/
|
||||
private int height;
|
||||
|
||||
/**
|
||||
* Applies to the projection to the longitude and latitue pairs and stores the results.
|
||||
*
|
||||
* @param projection The projection.
|
||||
* @param longitudes The longitudes of coordinates.
|
||||
* @param latitudes The latitudes of coordinates.
|
||||
* @param width The width of the image.
|
||||
* @param height The height of the image.
|
||||
*/
|
||||
public ImageProjection(IProjection projection, DoubleArray longitudes, DoubleArray latitudes, int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
int size = Math.min(longitudes.getSize(), latitudes.getSize());
|
||||
this.x = new IntArray(size);
|
||||
this.y = new IntArray(size);
|
||||
for (int i = 0; i < size; i++) {
|
||||
double latitude = latitudes.getValue(i);
|
||||
double longitude = longitudes.getValue(i);
|
||||
if (projection.isVisible(longitude, latitude)) {
|
||||
x.setValue(i,Math.max(0, (int)Math.round(Math.min(width - 1, projection.getX(longitude, latitude) * width))));
|
||||
y.setValue(i, Math.max(0, (int)Math.round(Math.min(height - 1, projection.getY(longitude, latitude) * height))));
|
||||
} else {
|
||||
x.setValue(i, -1);
|
||||
y.setValue(i, -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The width of the image.
|
||||
*
|
||||
* @return The width of the image.
|
||||
*/
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
/**
|
||||
* The height of the image.
|
||||
*
|
||||
* @return The height of the image.
|
||||
*/
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the i-th coordinate is visible.
|
||||
*
|
||||
* @param index The index.
|
||||
* @return True if visible, false otherwise.
|
||||
*/
|
||||
public boolean isVisible(int index) {
|
||||
return x.getValue(index) >= 0 && y.getValue(index) >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the x-coordinate of the i-th wgs coordinate
|
||||
* or -1, if it is not visible.
|
||||
*
|
||||
* @param index The index.
|
||||
* @return The x coordinate or -1 if not visible.
|
||||
*/
|
||||
public int getX(int index) {
|
||||
return x.getValue(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the y-coordinate of the i-th wgs coordinate
|
||||
* or -1, if it is not visible.
|
||||
*
|
||||
* @param index The index.
|
||||
* @return The y coordinate or -1 if not visible.
|
||||
*/
|
||||
public int getY(int index) {
|
||||
return y.getValue(index);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -165,9 +165,9 @@ public class VideoEncoder {
|
||||
*/
|
||||
private int height;
|
||||
/**
|
||||
* The bitrate.
|
||||
* The constant rate factor to set the target quality.
|
||||
*/
|
||||
private int bitrate;
|
||||
private int crf;
|
||||
/**
|
||||
* The quality preset of the encoder.
|
||||
*/
|
||||
@@ -207,17 +207,17 @@ public class VideoEncoder {
|
||||
* @param height The height of the video and the input images.
|
||||
* @param format The image format that defines the pixel layout and the number of bytes per pixel.
|
||||
* @param fps The play back speed in frames per second.
|
||||
* @param bitrate The target bitrate in kbs.
|
||||
* @param crf The constant rate factor between 0 (no compression) to 51 (high loss, small size).
|
||||
* @param quality The quality preset to balance the encoder quality and processing effort.
|
||||
*
|
||||
* @throws IOException Thrown if the allocation of the various objects fails.
|
||||
* @throws NullPointerException Thrown if the quality preset or image format is null.
|
||||
* @throws IllegalArgumentException Thrown if the width, height, fps or bitrate is not positive.
|
||||
*/
|
||||
public VideoEncoder(int width, int height, PixelFormat format, int fps, int bitrate, Quality quality) throws IOException {
|
||||
public VideoEncoder(int width, int height, PixelFormat format, int fps, int crf, Quality quality) throws IOException {
|
||||
if (width <= 0) throw new IllegalArgumentException("Invalid image width (" + width + "), must be positive.");
|
||||
if (height <= 0) throw new IllegalArgumentException("Invalid image height (" + height + "), must be positive.");
|
||||
if (bitrate <= 0) throw new IllegalArgumentException("Invalid bitrate (" + bitrate + "), must be positive.");
|
||||
if (crf < 0 || crf > 51) throw new IllegalArgumentException("Invalid crf (" + crf + "), must be (good) 0-51 (bad).");
|
||||
if (fps <= 0) throw new IllegalArgumentException("Invalid fps (" + fps + "), must be positive.");
|
||||
if (format == null) throw new NullPointerException("Image format must not be null.");
|
||||
if (quality == null) throw new NullPointerException("Quality preset must not be null.");
|
||||
@@ -227,7 +227,7 @@ public class VideoEncoder {
|
||||
this.format = format;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.bitrate = bitrate;
|
||||
this.crf = crf;
|
||||
this.quality = quality;
|
||||
|
||||
logger.log(Level.FINEST, "Configuring log level.");
|
||||
@@ -256,7 +256,6 @@ public class VideoEncoder {
|
||||
videoStream.codecpar().width(width);
|
||||
videoStream.codecpar().height(height);
|
||||
videoStream.codecpar().format(avutil.AV_PIX_FMT_YUV420P); // change format
|
||||
videoStream.codecpar().bit_rate(bitrate * 1000);
|
||||
AVRational timeBase = avutil.av_make_q(1, fps);
|
||||
codecContext.time_base(timeBase);
|
||||
videoStream.time_base(timeBase);
|
||||
@@ -271,6 +270,8 @@ public class VideoEncoder {
|
||||
if (error < 0) throw new IOException("Could not apply codec param.");
|
||||
error = avutil.av_opt_set(codecContext, "b_strategy", "2", avutil.AV_OPT_SEARCH_CHILDREN);
|
||||
if (error < 0) throw new IOException("Could not apply codec param.");
|
||||
error = avutil.av_opt_set(codecContext, "crf", Integer.toString(crf), avutil.AV_OPT_SEARCH_CHILDREN);
|
||||
if (error < 0) throw new IOException("Could not apply codec param.");
|
||||
}
|
||||
logger.log(Level.FINEST, "Setting format header flags.");
|
||||
if ((formatContext.oformat().flags() & avformat.AVFMT_GLOBALHEADER) != 0) {
|
||||
@@ -392,12 +393,12 @@ public class VideoEncoder {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the target bitrate of the encoder.
|
||||
* Returns the constant rate factor of the encoder.
|
||||
*
|
||||
* @return The target bitrate of the encoder.
|
||||
* @return The constant rate factor of the encoder.
|
||||
*/
|
||||
public int getBitrate() {
|
||||
return bitrate;
|
||||
public int getCrf() {
|
||||
return crf;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -277,7 +277,7 @@ public abstract class AbstractLocationEntity extends AbstractSpatialEntity {
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<AbstractLocationEntity> findAllByTerm(EntityManager em, PageConfig config, Language language, String term) {
|
||||
FullTextQuery query = createQueryByTerm(em, language, term);
|
||||
query.setSort(new Sort(SortField.FIELD_SCORE, new SortField("importance", Type.DOUBLE, true), new SortField("addressRank", Type.INT)));
|
||||
query.setSort(new Sort(SortField.FIELD_SCORE, new SortField("importance", Type.DOUBLE, true), new SortField("searchRank", Type.INT)));
|
||||
query.setFirstResult(config.getOffset());
|
||||
query.setMaxResults(config.getSize());
|
||||
query.setProjection(FullTextQuery.OBJECT_CLASS, FullTextQuery.ID, FullTextQuery.DOCUMENT_ID, FullTextQuery.SCORE);
|
||||
|
||||
@@ -10,7 +10,6 @@ import javax.annotation.security.DeclareRoles;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ejb.Stateless;
|
||||
import javax.inject.Inject;
|
||||
import javax.websocket.ClientEndpoint;
|
||||
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
|
||||
+11
-4
@@ -9,6 +9,7 @@ import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Comparator;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -105,16 +106,22 @@ public class WeatherVideoSyncSessionBean extends AbstractSyncSessionBean {
|
||||
*/
|
||||
private static List<WeatherVideo> getFiltered(List<WeatherVideo> videos, boolean filter) {
|
||||
if (!filter) return videos;
|
||||
Map<WeatherSource, Long> latest = new HashMap<>();
|
||||
Map<WeatherSource, Map<VideoType, Long>> latest = new HashMap<>();
|
||||
for (WeatherVideo v: videos) {
|
||||
Long ts = latest.get(v.getSource());
|
||||
Map<VideoType, Long> map = latest.get(v.getSource());
|
||||
if (map == null) {
|
||||
map = new EnumMap<>(VideoType.class);
|
||||
latest.put(v.getSource(), map);
|
||||
}
|
||||
Long ts = map.get(v.getType());
|
||||
if (ts == null || ts < v.getTime()) {
|
||||
latest.put(v.getSource(), v.getTime());
|
||||
map.put(v.getType(), v.getTime());
|
||||
}
|
||||
}
|
||||
for (int i = videos.size() - 1; i >= 0; i--) {
|
||||
WeatherVideo v = videos.get(i);
|
||||
Long ts = latest.get(v.getSource());
|
||||
Map<VideoType, Long> map = latest.get(v.getSource());
|
||||
Long ts = map.get(v.getType());
|
||||
if (v.getTime() < ts) {
|
||||
videos.remove(i);
|
||||
}
|
||||
|
||||
@@ -12,5 +12,19 @@ dependencies {
|
||||
compile "org.jboss.resteasy:resteasy-jackson2-provider:${versionResteasy}"
|
||||
compile 'postgresql:postgresql:8.4-701.jdbc3'
|
||||
compile 'net.iakovlev:timeshape:2019b.7'
|
||||
compile 'commons-cli:commons-cli:1.4'
|
||||
|
||||
|
||||
// builds a jar with all dependencies for the nominatim exporter so
|
||||
// we can transfer the code to oz and run it there which is significantly
|
||||
// faster than running it at home through a vpn (which may fail 8-P).
|
||||
task nominatimExporter(type: Jar) {
|
||||
classifier = 'nominatim'
|
||||
manifest {
|
||||
attributes 'Main-Class': 'com.mowesta.tool.nominatim.NominatimExporter'
|
||||
}
|
||||
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
|
||||
with jar
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
package com.mowesta.tool.model;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.DefaultParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Option;
|
||||
import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.cli.ParseException;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
|
||||
/**
|
||||
* A tool that analyzes measurements downloaded with the measurement
|
||||
* downloader and generates csv files for further analysis.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class MeasurementAnalyzer {
|
||||
|
||||
/**
|
||||
* The filename pattern of files to be loaded.
|
||||
*/
|
||||
private static String FILENAME_PATTERN = "measurement-([0-9])+.json";
|
||||
|
||||
/**
|
||||
* The default output directory of the tool.
|
||||
*/
|
||||
private static final String DEFAULT_OUTPUT_DIRECTORY = "data";
|
||||
|
||||
/**
|
||||
* The default input directory of the tool.
|
||||
*/
|
||||
private static final String DEFAULT_INPUT_DIRECTORY = "data";
|
||||
|
||||
/**
|
||||
* The logger used to generate the output.
|
||||
*/
|
||||
private static Logger log = Logger.getLogger(MeasurementAnalyzer.class.getName());
|
||||
|
||||
/**
|
||||
* The table structure which we generate during the analysis.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class MeasurementItem {
|
||||
|
||||
/** The id of the device. */
|
||||
public long device;
|
||||
|
||||
/** The time of the measurement. */
|
||||
public long time;
|
||||
|
||||
/** The battery temperature. */
|
||||
public double temperature;
|
||||
|
||||
/** The state of the interactive flag. */
|
||||
public boolean interactive;
|
||||
|
||||
/** The state of the charging flag. */
|
||||
public boolean charging;
|
||||
|
||||
/** The battery voltage. */
|
||||
public double voltage;
|
||||
|
||||
/** The average cpu frequency. */
|
||||
public double avgFrequency;
|
||||
|
||||
/** The maximum cpu frequency. */
|
||||
public double maxFrequency;
|
||||
|
||||
/** The absolute temperature difference between the previous reading divided by time difference. */
|
||||
public double deltaTemperature;
|
||||
|
||||
/** The time in milliseconds that this device has not been charged or interactive. */
|
||||
public long idleDuration;
|
||||
|
||||
/** The longitude of the measurement. */
|
||||
public double longitude;
|
||||
|
||||
/** The latitude of the measurement. */
|
||||
public double latitude;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
try {
|
||||
StringBuilder b = new StringBuilder();
|
||||
Field[] fields = getClass().getDeclaredFields();
|
||||
for (Field f: fields) {
|
||||
f.setAccessible(true);
|
||||
b.append(f.getName() + "=" + f.get(this));
|
||||
b.append(" ");
|
||||
}
|
||||
return b.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize fields.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the field names separated by the separator.
|
||||
*
|
||||
* @param separator The separator.
|
||||
* @return The field names.
|
||||
*/
|
||||
public static String getFields(String separator) {
|
||||
try {
|
||||
StringBuilder b = new StringBuilder();
|
||||
Field[] fields = MeasurementItem.class.getDeclaredFields();
|
||||
for (Field f: fields) {
|
||||
b.append(f.getName());
|
||||
b.append(separator);
|
||||
}
|
||||
return b.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize fields.", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param separator The separator.
|
||||
* @return The values.
|
||||
*/
|
||||
public String getValues(String separator) {
|
||||
try {
|
||||
StringBuilder b = new StringBuilder();
|
||||
Field[] fields = getClass().getDeclaredFields();
|
||||
for (Field f: fields) {
|
||||
f.setAccessible(true);
|
||||
b.append(f.get(this));
|
||||
b.append(separator);
|
||||
}
|
||||
return b.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize fields.", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public class Aggregate {
|
||||
|
||||
private List<Double> values = new ArrayList<>();
|
||||
|
||||
private void add(double value) {
|
||||
this.values.add(value);
|
||||
}
|
||||
|
||||
public int count() {
|
||||
return values.size();
|
||||
}
|
||||
|
||||
public Double average() {
|
||||
if (values.isEmpty()) return null;
|
||||
double sum = 0;
|
||||
for (Double v: values) {
|
||||
sum += v;
|
||||
}
|
||||
return sum / values.size();
|
||||
}
|
||||
|
||||
public Double variance() {
|
||||
Double average = average();
|
||||
if (average == null)
|
||||
return null;
|
||||
double var = 0;
|
||||
for (Double v: values) {
|
||||
double dx = average - v;
|
||||
var += dx * dx;
|
||||
}
|
||||
return Math.sqrt(var / values.size());
|
||||
}
|
||||
|
||||
public Double max() {
|
||||
Double max = null;
|
||||
for (Double v: values)
|
||||
if (max == null || max < v)
|
||||
max = v;
|
||||
return max;
|
||||
}
|
||||
|
||||
public Double min() {
|
||||
Double min = null;
|
||||
for (Double v: values)
|
||||
if (min == null || min > v)
|
||||
min = v;
|
||||
return min;
|
||||
}
|
||||
|
||||
public Double[] percentiles(int numbers) {
|
||||
if (values.isEmpty()) return null;
|
||||
List<Double> sorted = new ArrayList<>(values);
|
||||
Collections.sort(sorted);
|
||||
Double[] result = new Double[numbers - 1];
|
||||
for (int i = 1; i < numbers; i++) {
|
||||
result[i - 1] = sorted.get((int)(Math.max(0, Math.min(sorted.size() - 1, sorted.size() * (i / (double)numbers)))));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder b = new StringBuilder();
|
||||
b.append("Count: ");
|
||||
b.append(count());
|
||||
b.append(" Average: ");
|
||||
b.append(average());
|
||||
b.append(" Variance: ");
|
||||
b.append(variance());
|
||||
b.append(" Min: ");
|
||||
b.append(min());
|
||||
b.append(" Max: ");
|
||||
b.append(max());
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The list of items.
|
||||
*/
|
||||
private List<MeasurementItem> items = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Creates a new analyzer.
|
||||
*
|
||||
* @param measurements The measurements.
|
||||
*/
|
||||
public MeasurementAnalyzer(List<Measurement> measurements) {
|
||||
Collections.sort(measurements, (a, b) -> (int)(a.getTime() - b.getTime()));
|
||||
for (int i = 1; i < measurements.size(); i++) {
|
||||
Measurement p = measurements.get(i - 1);
|
||||
Measurement c = measurements.get(i);
|
||||
try {
|
||||
MeasurementItem item = new MeasurementItem();
|
||||
item.device = c.getDevice();
|
||||
item.time = c.getTime();
|
||||
item.temperature = getDouble(c, MeasurementType.BATTERY_TEMPERATURE);
|
||||
item.charging = getBoolean(c, MeasurementType.BATTERY_CHARGING);
|
||||
item.interactive = getBoolean(c, MeasurementType.SCREEN_ENABLED);
|
||||
item.voltage = getDouble(c, MeasurementType.BATTERY_VOLTAGE);
|
||||
item.avgFrequency = getAverage(c, MeasurementType.CPU_FREQUENCY);
|
||||
item.maxFrequency = getMaximum(c, MeasurementType.CPU_FREQUENCY);
|
||||
item.longitude = c.getCoordinate().getLongitude();
|
||||
item.latitude = c.getCoordinate().getLatitude();
|
||||
double pt = getDouble(p, MeasurementType.BATTERY_TEMPERATURE);
|
||||
long dx = c.getTime() - p.getTime();
|
||||
item.deltaTemperature = Math.abs(item.temperature - pt) / dx;
|
||||
if (item.charging || item.interactive) {
|
||||
item.idleDuration = 0;
|
||||
} else {
|
||||
item.idleDuration = dx;
|
||||
if (items.size() > 0) {
|
||||
item.idleDuration += items.get(items.size() - 1).idleDuration;
|
||||
}
|
||||
}
|
||||
items.add(item);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.println(c.toString());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a boolean value from a measurement for a given type.
|
||||
*
|
||||
* @param m The measurement.
|
||||
* @param t The type.
|
||||
* @return The boolean for the type.
|
||||
*/
|
||||
private boolean getBoolean(Measurement m, MeasurementType t) {
|
||||
return (Boolean)(getValues(m, t)[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a double value from a measurement for a given type.
|
||||
*
|
||||
* @param m The measurement.
|
||||
* @param t The type.
|
||||
* @return The double for the type.
|
||||
*/
|
||||
private double getDouble(Measurement m, MeasurementType t) {
|
||||
return (Double)(getValues(m, t)[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum value of a measurement for a given type.
|
||||
*
|
||||
* @param m The measurement.
|
||||
* @param t The type.
|
||||
* @return The maximum value for the type.
|
||||
*/
|
||||
private double getMaximum(Measurement m, MeasurementType t) {
|
||||
Object[] values = getValues(m, t);
|
||||
Double max = null;
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
if (max == null || max < (Double)values[i]) max = (Double)values[i];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the average value of a measurement for a given type.
|
||||
*
|
||||
* @param m The measurement.
|
||||
* @param t The type.
|
||||
* @return The average value for the type.
|
||||
*/
|
||||
private double getAverage(Measurement m, MeasurementType t) {
|
||||
Object[] values = getValues(m, t);
|
||||
double sum = 0;
|
||||
for (Object d: values) {
|
||||
sum += (Double)d;
|
||||
}
|
||||
return sum / values.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the values of a measurement for a given type.
|
||||
*
|
||||
* @param m The measurement.
|
||||
* @param t The type.
|
||||
* @return The values for the type.
|
||||
*/
|
||||
private Object[] getValues(Measurement m, MeasurementType t) {
|
||||
return t.getValues(m.getData().get(t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the data in a new aggregate.
|
||||
*
|
||||
* @param filter The filter.
|
||||
* @param extractor The extractor.
|
||||
* @return The aggregate.
|
||||
*/
|
||||
private Aggregate extract(Filter filter, Extractor extractor) {
|
||||
Aggregate result = new Aggregate();
|
||||
extract(result, filter, extractor);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the data into a given aggregate.
|
||||
*
|
||||
* @param result The result.
|
||||
* @param filter The filter.
|
||||
* @param extractor The extractor.
|
||||
*/
|
||||
private void extract(Aggregate result, Filter filter, Extractor extractor) {
|
||||
for (MeasurementItem it: items) {
|
||||
if (filter.include(it)) {
|
||||
result.add(extractor.getValue(it));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Runs the program.
|
||||
*
|
||||
* @param args The command line arguments.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Options options = new Options();
|
||||
|
||||
Option inputOption = new Option("i", "input", true, "The source folder to load the data.");
|
||||
options.addOption(inputOption);
|
||||
|
||||
Option outputOption = new Option("o", "output", true, "The output folder to store the data.");
|
||||
options.addOption(outputOption);
|
||||
|
||||
CommandLineParser parser = new DefaultParser();
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
|
||||
Map<File, MeasurementAnalyzer> measurements = new HashMap<>();
|
||||
|
||||
try {
|
||||
CommandLine cmd = parser.parse(options, args);
|
||||
String output = cmd.getOptionValue(outputOption.getOpt(), null);
|
||||
File outputDirectory = output == null ? new File(DEFAULT_OUTPUT_DIRECTORY) : new File(output);
|
||||
log.log(Level.INFO, String.format("Using output folder %s.", outputDirectory.getAbsolutePath()));
|
||||
String input = cmd.getOptionValue(inputOption.getOpt(), null);
|
||||
File inputDirectory = input == null ? new File(DEFAULT_INPUT_DIRECTORY) : new File(input);
|
||||
log.log(Level.INFO, String.format("Using input folder %s.", inputDirectory.getAbsolutePath()));
|
||||
if (!outputDirectory.exists()) outputDirectory.mkdirs();
|
||||
File[] files = inputDirectory.listFiles();
|
||||
if (files != null) {
|
||||
for (File file: files) {
|
||||
if (file.getName().matches(FILENAME_PATTERN)) {
|
||||
List<Measurement> m = loadMeasurements(file);
|
||||
if (m != null) measurements.put(file, new MeasurementAnalyzer(m));
|
||||
}
|
||||
}
|
||||
}
|
||||
String separator = ";";
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputDirectory, "data.csv")))) {
|
||||
writer.write(MeasurementItem.getFields(separator));
|
||||
writer.newLine();
|
||||
for (MeasurementAnalyzer ma: measurements.values()) {
|
||||
for (MeasurementItem m: ma.items) {
|
||||
writer.write(m.getValues(separator));
|
||||
System.out.println(m.getValues(separator));
|
||||
writer.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp(MeasurementAnalyzer.class.getSimpleName(), options);
|
||||
System.exit(1);
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
for (MeasurementAnalyzer a: measurements.values()) {
|
||||
System.out.println(a.items.get(0).latitude + "," + a.items.get(0).longitude);
|
||||
Aggregate deltaTemperatureIdle = a.extract((m) -> m.idleDuration > 1000 * 60 * 60, (m) -> m.temperature);
|
||||
Aggregate deltaTemperatureUsed = a.extract((m) -> m.idleDuration <= 1000 * 60 * 60, (m) -> m.temperature);
|
||||
|
||||
System.out.println("Idle: " + deltaTemperatureIdle);
|
||||
System.out.println("Used: " + deltaTemperatureUsed);
|
||||
System.out.println();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to load a list of measurements.
|
||||
*
|
||||
* @param file The file.
|
||||
* @return The measurements or null, if the file cannot be read.
|
||||
*/
|
||||
private static List<Measurement> loadMeasurements(File file) {
|
||||
log.log(Level.INFO, String.format("Reading file %s.", file.getAbsolutePath()));
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
|
||||
List<Measurement> result = new ArrayList<>();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, Measurement.class));
|
||||
}
|
||||
log.log(Level.INFO, String.format("Returning %d measurements.", result.size()));
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
log.log(Level.WARNING, String.format("Failed to read file %s.", file.getAbsolutePath()), e);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private interface Extractor {
|
||||
Double getValue(MeasurementItem item);
|
||||
}
|
||||
|
||||
private interface Filter {
|
||||
boolean include(MeasurementItem item);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package com.mowesta.tool.model;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.DefaultParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Option;
|
||||
import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.cli.ParseException;
|
||||
import org.jboss.resteasy.client.jaxrs.BasicAuthentication;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
|
||||
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
|
||||
import org.jboss.resteasy.client.jaxrs.engines.URLConnectionEngine;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mowesta.api.PageConfig;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.IMeasurementService;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementPage;
|
||||
|
||||
/**
|
||||
* A tool to download the measurements of a number of devices.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class MeasurementDownloader {
|
||||
|
||||
// 1161281,9569042,9660419,9732599,9870388,9934728,9939081,10108047,10108047,10312353,10381889,10880985
|
||||
|
||||
/**
|
||||
* The url of the MoWeSta api.
|
||||
*/
|
||||
public static final String API_URL = "https://www.mowesta.com/api";
|
||||
|
||||
/**
|
||||
* The page size used for downloads.
|
||||
*/
|
||||
private static final int PAGE_SIZE = 500;
|
||||
|
||||
/**
|
||||
* The default output directory of the tool.
|
||||
*/
|
||||
private static final String DEFAULT_OUTPUT_DIRECTORY = "data";
|
||||
|
||||
/**
|
||||
* The logger used to generate the output.
|
||||
*/
|
||||
private static Logger log = Logger.getLogger(MeasurementDownloader.class.getName());
|
||||
|
||||
/**
|
||||
* The output folder.
|
||||
*/
|
||||
private File outputFolder;
|
||||
|
||||
/**
|
||||
* The devices.
|
||||
*/
|
||||
private List<Long> devices;
|
||||
|
||||
/**
|
||||
* The measurement service.
|
||||
*/
|
||||
private IMeasurementService service;
|
||||
|
||||
/**
|
||||
* Creates a new downloader.
|
||||
*
|
||||
* @param username The user name.
|
||||
* @param password The password.
|
||||
* @param outputFolder The output folder.
|
||||
* @param devices The device ids to download.
|
||||
*/
|
||||
public MeasurementDownloader(String username, String password, File outputFolder, List<Long> devices) {
|
||||
this.outputFolder = outputFolder;
|
||||
this.devices = devices;
|
||||
ResteasyClientBuilder builder = new ResteasyClientBuilder();
|
||||
builder.httpEngine(new URLConnectionEngine());
|
||||
ResteasyWebTarget target = builder.build().target(API_URL);
|
||||
target.register(new BasicAuthentication(username, password));
|
||||
service = target.proxy(IMeasurementService.class);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Downloads all device data in the time range.
|
||||
*
|
||||
* @param range The time range.
|
||||
* @throws Exception Thrown if the download fails.
|
||||
*/
|
||||
public void download(TimeRange range) throws Exception {
|
||||
for (Long device: devices) {
|
||||
download(range, device, getOutputFile(device));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output file for the device.
|
||||
*
|
||||
* @param device The device id.
|
||||
* @return The output file.
|
||||
*/
|
||||
private File getOutputFile(long device) {
|
||||
return new File(outputFolder, String.format("measurement-%d.json", device));
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the data for a single device.
|
||||
*
|
||||
* @param range The time range.
|
||||
* @param device The device id.
|
||||
* @param outputFile The target file.
|
||||
* @throws Exception Thrown if the download fails.
|
||||
*/
|
||||
private void download(TimeRange range, long device, File outputFile) throws Exception {
|
||||
log.log(Level.INFO, String.format("Downloading measurements for device %s.", device));
|
||||
int measurementCount = 0;
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
PageConfig config = new PageConfig(0, PAGE_SIZE);
|
||||
while (true) {
|
||||
Response response = service.getDeviceMeasurements(device, range, config);
|
||||
MeasurementPage page = response.readEntity(MeasurementPage.class);
|
||||
if (page.getElements().size() > 0) {
|
||||
for (Measurement m : page.getElements()) {
|
||||
writer.write(mapper.writeValueAsString(m));
|
||||
writer.newLine();
|
||||
measurementCount += 1;
|
||||
}
|
||||
config.setOffset(config.getOffset() + page.getSize());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
writer.close();
|
||||
}
|
||||
log.log(Level.INFO, String.format("Wrote %d measurements to %s.", measurementCount, outputFile.getAbsolutePath()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The main method that runs the downloader with command line parameters.
|
||||
*
|
||||
* @param args The arguments.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
Options options = new Options();
|
||||
|
||||
Option usernameOption = new Option("u", "username", true, "The username of a MoWeSta user with sufficient privileges to access the data.");
|
||||
usernameOption.setRequired(true);
|
||||
options.addOption(usernameOption);
|
||||
|
||||
Option passwordOption = new Option("p", "password", true, "The password of the MoWeSta user.");
|
||||
passwordOption.setRequired(true);
|
||||
options.addOption(passwordOption);
|
||||
|
||||
Option outputOption = new Option("o", "output", true, "The destination folder to store the downloaded data.");
|
||||
options.addOption(outputOption);
|
||||
|
||||
Option devicesOption = new Option("d", "devices", true, "The device id(s) to download, separated by a comma or given as multiple arguments.");
|
||||
devicesOption.setRequired(true);
|
||||
options.addOption(devicesOption);
|
||||
|
||||
CommandLineParser parser = new DefaultParser();
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
|
||||
MeasurementDownloader downloader;
|
||||
|
||||
try {
|
||||
CommandLine cmd = parser.parse(options, args);
|
||||
String username = cmd.getOptionValue(usernameOption.getOpt());
|
||||
String password = cmd.getOptionValue(passwordOption.getOpt());
|
||||
String output = cmd.getOptionValue(outputOption.getOpt(), null);
|
||||
File file = output == null ? new File(DEFAULT_OUTPUT_DIRECTORY) : new File(output);
|
||||
log.log(Level.INFO, String.format("Using output folder %s.", file.getAbsolutePath()));
|
||||
if (!file.exists()) file.mkdirs();
|
||||
Set<Long> devices = new HashSet<>();
|
||||
for (String string: cmd.getOptionValues(devicesOption.getOpt())) {
|
||||
for (String token: string.split(",")) {
|
||||
Long data = Long.valueOf(token.trim());
|
||||
if (data == null) {
|
||||
log.log(Level.WARNING, String.format("Ignoring illegal device id %s.", token.trim()));
|
||||
continue;
|
||||
}
|
||||
if (! devices.add(data)) {
|
||||
log.log(Level.WARNING, String.format("Ignoring duplicate device id %s.", token.trim()));
|
||||
}
|
||||
}
|
||||
}
|
||||
List<Long> list = new ArrayList<>(devices);
|
||||
Collections.sort(list);
|
||||
downloader = new MeasurementDownloader(username, password, file, list);
|
||||
} catch (ParseException e) {
|
||||
System.out.println(e.getMessage());
|
||||
formatter.printHelp(MeasurementDownloader.class.getSimpleName(), options);
|
||||
System.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
downloader.download(new TimeRange(0, System.currentTimeMillis()));
|
||||
} catch (Exception e) {
|
||||
log.log(Level.SEVERE, "Failed to download data.", e);
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -101,6 +101,12 @@ public class NominatimExporter {
|
||||
*/
|
||||
public static final String FILE_DUPLICATES = "duplicates.json";
|
||||
|
||||
/**
|
||||
* The file that contains the resolved city names.
|
||||
*/
|
||||
public static final String FILE_RENAME = "cities-renamed.json";
|
||||
|
||||
|
||||
/**
|
||||
* Timezone Engine for determine timezone at specific coordinate
|
||||
*/
|
||||
@@ -157,6 +163,9 @@ public class NominatimExporter {
|
||||
logger.log(Level.INFO, "Computing duplicate cities.");
|
||||
counter = computeDuplicateCities(new File(FILE_CITIES), new File(FILE_DUPLICATES));
|
||||
logger.log(Level.INFO, "Found " + counter + " duplicate cities.");
|
||||
counter = renameCityNames(new File(FILE_DUPLICATES), new File(FILE_CITIES), new File(FILE_RENAME));
|
||||
logger.log(Level.INFO, "Renamed " + counter + " cities.");
|
||||
|
||||
} finally {
|
||||
Database.close();
|
||||
}
|
||||
@@ -195,6 +204,7 @@ public class NominatimExporter {
|
||||
city.setAddressRank(place.getAddressRank());
|
||||
city.setSearchRank(place.getSearchRank());
|
||||
city.setWikipedia(place.getWikipedia());
|
||||
city.setInside(place.getAddress().get("is_in"));
|
||||
city.setNames(getFilteredNames(place.getNames()));
|
||||
if (place.getCentroid() != null)
|
||||
city.setCentroid(toPoint(place.getCentroid()));
|
||||
@@ -225,7 +235,7 @@ public class NominatimExporter {
|
||||
logger.log(Level.INFO, "Ingnoring city due to invalid country code: " + countryCode);
|
||||
continue;
|
||||
}
|
||||
if (city.getType() != CityType.CITY && city.getType() != CityType.TOWN && !countryCode.equalsIgnoreCase("de")) {
|
||||
if (shouldExcludeCity(city, countryCode)) {
|
||||
// silently ignore smaller places outside of germany
|
||||
continue;
|
||||
}
|
||||
@@ -241,6 +251,7 @@ public class NominatimExporter {
|
||||
}
|
||||
}
|
||||
}
|
||||
city.setParent(findParentName(parents));
|
||||
String timezone = getTimezoneByCoordinate(city.getCentroid());
|
||||
if (timezone == null) {
|
||||
logger.log(Level.SEVERE, "Unable to find timezone for city: " + city.getCentroid() + ". Skipping.");
|
||||
@@ -251,7 +262,6 @@ public class NominatimExporter {
|
||||
if (city.getBoundary() == null) {
|
||||
logger.log(Level.INFO, "Could not find boundary for city: " + countryCode + ":" + city.getNames().get("name"));
|
||||
}
|
||||
|
||||
writer.write(objectMapper.writeValueAsString(city));
|
||||
writer.write("\n");
|
||||
counter += 1;
|
||||
@@ -273,6 +283,39 @@ public class NominatimExporter {
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first id of a city or a town in the places list.
|
||||
*
|
||||
* @param places The places to search.
|
||||
* @return The first id of a city or a town.
|
||||
*/
|
||||
private static String findParentName(List<PlaceEntity> places) {
|
||||
for (PlaceEntity p: places) {
|
||||
String name = p.getNames().get("name");
|
||||
if (name != null) return name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether the city should be excluded from the import based on the
|
||||
* city (type) and the country code.
|
||||
*
|
||||
* @param city The city.
|
||||
* @param countryCode The country code.
|
||||
* @return True if the city should not be imported, false otherwise.
|
||||
*/
|
||||
private static boolean shouldExcludeCity(NominatimCity city, String countryCode) {
|
||||
if (city.getType() == CityType.CITY) return false;
|
||||
if (city.getType() == CityType.TOWN) return false;
|
||||
if (countryCode.equalsIgnoreCase("de")) return false;
|
||||
if (countryCode.equalsIgnoreCase("at")) return false;
|
||||
if (countryCode.equalsIgnoreCase("ch")) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a map containing the names filtered by languages that we care about.
|
||||
*
|
||||
@@ -395,7 +438,9 @@ public class NominatimExporter {
|
||||
// regular level, "kreisfreie stadt", new york
|
||||
if ("de".equals(countryCode.toLowerCase())) {
|
||||
// Kreisfreie Stadt
|
||||
if (p.getAdminLevel() == 6) return true;
|
||||
if (city.getType() == CityType.CITY && p.getAdminLevel() == 6) {
|
||||
return true;
|
||||
}
|
||||
// Hansestadt Hamburg (Stadtstaat)
|
||||
if (city.getNames().containsValue("Hamburg")) {
|
||||
return p.getAdminLevel() == 4;
|
||||
@@ -410,8 +455,15 @@ public class NominatimExporter {
|
||||
return p.getAdminLevel() == 5;
|
||||
}
|
||||
}
|
||||
// regular level in most countries
|
||||
return p.getAdminLevel() >= 8;
|
||||
switch (city.getType()) {
|
||||
case SUBURB:
|
||||
case VILLAGE:
|
||||
// must be higher than city level
|
||||
return p.getAdminLevel() >= 9;
|
||||
default:
|
||||
// regular level in most countries
|
||||
return p.getAdminLevel() >= 8;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -780,7 +832,100 @@ public class NominatimExporter {
|
||||
return (Math.abs(lat1 - lat2) < 0.01 && Math.abs(lon1 - lon2) < 0.01);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Implements heuristics to rename the towns and suburbs that are non-unique
|
||||
* to something unique.
|
||||
*
|
||||
* @param dups The duplicates to ignore.
|
||||
* @param input The input with the cities.
|
||||
* @param output The output with the adapted cities.
|
||||
* @return The number of renames.
|
||||
* @throws Exception Thrown if something fails.
|
||||
*/
|
||||
private static int renameCityNames(File dups, File input, File output) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
Set<Long> duplicates = new HashSet<>();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(dups), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
NominatimCity city = mapper.readValue(line, NominatimCity.class);
|
||||
duplicates.add(city.getId());
|
||||
}
|
||||
}
|
||||
Map<String, List<NominatimCity>> cities = new HashMap<>();
|
||||
Map<Long, NominatimCity> parents = new HashMap<>();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
NominatimCity city = mapper.readValue(line, NominatimCity.class);
|
||||
// reduce the data size
|
||||
if (city.getBoundary() != null) {
|
||||
city.getBoundary().getCoordinates().clear();
|
||||
}
|
||||
parents.put(city.getId(), city);
|
||||
// do not handle cities in the duplicate set
|
||||
if (duplicates.contains(city.getId())) continue;
|
||||
// hash cities by state, country and name to detect collisions
|
||||
String key = "|" + city.getCountry();
|
||||
if (city.getState() != null) {
|
||||
key += "|" + city.getState();
|
||||
}
|
||||
key += "|" + city.getNames().get("name");
|
||||
List<NominatimCity> c = cities.get(key);
|
||||
if (c == null) {
|
||||
c = new ArrayList<>();
|
||||
cities.put(key, c);
|
||||
}
|
||||
c.add(city);
|
||||
}
|
||||
}
|
||||
Map<Long, NominatimCity> renamed = new HashMap<>();
|
||||
for (String key: cities.keySet()) {
|
||||
List<NominatimCity> collisions = cities.get(key);
|
||||
if (collisions.size() > 1) {
|
||||
for (int i = collisions.size() - 1; i >= 0; i--) {
|
||||
NominatimCity c = collisions.get(i);
|
||||
if (c.getType() == CityType.VILLAGE || c.getType() == CityType.SUBURB) {
|
||||
collisions.remove(i);
|
||||
String p = c.getParent();
|
||||
if (c.getInside() != null) {
|
||||
p = c.getInside().split(",")[0];
|
||||
}
|
||||
p = p.split("\\(")[0].trim();
|
||||
p = p.split(";")[0];
|
||||
if (p.startsWith("Samtgemeinde") || p.startsWith("Landkreis") || p.startsWith("Verwaltungsgemeinschaft")
|
||||
|| p.startsWith("Verwaltungsverband") || p.startsWith("Gemeindeverwaltungsverband")
|
||||
|| p.startsWith("Gemeinde") || p.startsWith("Bezirk")) {
|
||||
p = p.split(" ", 2)[1];
|
||||
}
|
||||
for (String s : new HashSet<>(c.getNames().keySet())) {
|
||||
c.getNames().put(s, c.getNames().get(s) + " (" + p.trim() + ")");
|
||||
}
|
||||
renamed.put(c.getId(), c);
|
||||
}
|
||||
}
|
||||
// remaining 3332 city/town collisions (mostly chinese)
|
||||
// if (collisions.size() > 1) {
|
||||
// counter += collisions.size();
|
||||
// }
|
||||
}
|
||||
}
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), StandardCharsets.UTF_8))) {
|
||||
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
NominatimCity city = mapper.readValue(line, NominatimCity.class);
|
||||
if (renamed.get(city.getId()) != null) {
|
||||
city.setNames(renamed.get(city.getId()).getNames());
|
||||
}
|
||||
writer.write(mapper.writeValueAsString(city));
|
||||
writer.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
return renamed.size();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
package com.mowesta.tool.process;
|
||||
|
||||
import com.mowesta.data.process.color.CloudDepthColorScheme;
|
||||
import com.mowesta.data.process.color.PrecipitationColorScheme;
|
||||
import com.mowesta.data.process.color.PressureColorScheme;
|
||||
import com.mowesta.data.process.color.ScientificTemperatureColorScheme;
|
||||
import com.mowesta.data.process.color.WhiteCloudColorScheme;
|
||||
import com.mowesta.data.process.image.ColorScaleRenderer;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
@@ -16,37 +8,60 @@ import java.io.IOException;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.mowesta.data.process.color.CloudDepthColorScheme;
|
||||
import com.mowesta.data.process.color.PrecipitationColorScheme;
|
||||
import com.mowesta.data.process.color.PressureColorScheme;
|
||||
import com.mowesta.data.process.color.ScientificTemperatureColorScheme;
|
||||
import com.mowesta.data.process.image.ColorScaleRenderer;
|
||||
|
||||
/**
|
||||
* Generates the scale pictures.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class ImageScaleGenerator {
|
||||
|
||||
/** The width of the scale image in pixels. */
|
||||
public static int WIDTH = 500;
|
||||
/** The height of the scale image in pixels. */
|
||||
public static int HEIGHT = 50;
|
||||
|
||||
/** The font size. */
|
||||
public static float FONT_SIZE = 16f;
|
||||
|
||||
/** The minimum temperature to render. */
|
||||
public static double TEMP_MIN = -40;
|
||||
/** The maximum temperature to render. */
|
||||
public static double TEMP_MAX = 40;
|
||||
/** The distance between temperature ticks. */
|
||||
public static double TEMP_TICK = 10;
|
||||
|
||||
/** The minimum cloud depth to render. */
|
||||
public static double CLOUD_MIN = 0;
|
||||
/** The maximum cloud depth to render. */
|
||||
public static double CLOUD_MAX = 1;
|
||||
/** The distance between cloud depth ticks. */
|
||||
public static double CLOUD_TICK = 0.1;
|
||||
|
||||
/** The minimum precipitation to render. */
|
||||
public static double PRECIPITATION_MIN = 0;
|
||||
/** The maximum precipitation to render. */
|
||||
public static double PRECIPITATION_MAX = 40;
|
||||
/** The distance between precipitation ticks. */
|
||||
public static double PRECIPITATION_TICK = 10;
|
||||
|
||||
/** The minimum pressure to render. */
|
||||
public static double PRESSURE_MIN = -1;
|
||||
/** The maximum pressure to render. */
|
||||
public static double PRESSURE_MAX = 1;
|
||||
/** The distance between pressure ticks. */
|
||||
public static double PRESSURE_TICK = 1;
|
||||
|
||||
/**
|
||||
* Generates the scale pictures.
|
||||
*
|
||||
*
|
||||
* @param args The arguments.
|
||||
* @throws IOException Thrown if an image cannot be saved.
|
||||
*/
|
||||
public static void main(String[] args) throws IOException {
|
||||
ColorScaleRenderer temp = new ColorScaleRenderer(new ScientificTemperatureColorScheme(), (v) -> String.format("%.0f°C", v));
|
||||
@@ -62,7 +77,7 @@ public class ImageScaleGenerator {
|
||||
render(cloud, "C:/users/marcus/desktop/cloud.png");
|
||||
|
||||
|
||||
ColorScaleRenderer precipitation = new ColorScaleRenderer(new PrecipitationColorScheme(), (v) -> String.format("%.0f kg/hm²", v));
|
||||
ColorScaleRenderer precipitation = new ColorScaleRenderer(new PrecipitationColorScheme(), (v) -> String.format("%.0f mm/h", v));
|
||||
precipitation.setMax(PRECIPITATION_MAX);
|
||||
precipitation.setMin(PRECIPITATION_MIN);
|
||||
precipitation.setTick(PRECIPITATION_TICK);
|
||||
@@ -70,9 +85,9 @@ public class ImageScaleGenerator {
|
||||
|
||||
|
||||
ColorScaleRenderer pressure = new ColorScaleRenderer(new PressureColorScheme(0, -1, 1), (v) -> {
|
||||
if (v == 0) return "Ø";
|
||||
if (v > 0) return "max";
|
||||
else return "min";
|
||||
if (v == 0) return "1013.25HPa";
|
||||
if (v > 0) return "+15HPa";
|
||||
else return "-15HPa";
|
||||
});
|
||||
pressure.setMax(PRESSURE_MAX);
|
||||
pressure.setMin(PRESSURE_MIN);
|
||||
@@ -80,6 +95,13 @@ public class ImageScaleGenerator {
|
||||
render(pressure, "C:/users/marcus/desktop/pressure.png");
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a color scale to the file name.
|
||||
*
|
||||
* @param renderer The renderer.
|
||||
* @param filename The file name.
|
||||
* @throws IOException Thrown if the image cannot be saved.
|
||||
*/
|
||||
public static void render(ColorScaleRenderer renderer, String filename) throws IOException {
|
||||
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D graphics = image.createGraphics();
|
||||
|
||||
@@ -48,9 +48,12 @@ public class VideoGeneratorExample {
|
||||
if (p.isAvailable(time)) {
|
||||
VideoGenerator videoGenerator = new VideoGenerator(p, c.createComposer(time));
|
||||
long start = System.currentTimeMillis();
|
||||
Variable variable = Variable.PREC;
|
||||
Variable variable = Variable.T2M;
|
||||
String name = "video-" + prefixes[i] + "-" + variable.getFolder();
|
||||
videoGenerator.createVideo(variable, time, 8, 16, new File(name + ".mp4"), new File(name + ".jpg"), (kfr, ifr)->{ return false;});
|
||||
videoGenerator.createVideo(variable, time, 8, 10, new File(name + ".mp4"), new File(name + ".jpg"), (kfr, ifr) -> {
|
||||
System.out.println("Key: " + kfr + " Int:" + ifr);
|
||||
return false;
|
||||
});
|
||||
System.out.println("Total duration: " + (System.currentTimeMillis() - start));
|
||||
} else {
|
||||
System.out.println("Prediction " + i + " is missing files?");
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start:forecast": "ng serve weather-forecast-today",
|
||||
"start:search": "ng serve weather-search",
|
||||
"build": "ng build",
|
||||
"build:forecast": "ng build --prod weather-forecast-today && npm run concat:forecast",
|
||||
"concat:forecast": "node ./ng-element-concat.js weather-forecast-today",
|
||||
|
||||
@@ -17,6 +17,7 @@ import { MatAutocompleteModule } from '@angular/material/autocomplete';
|
||||
import { WeatherSearchComponent } from './weather-search/weather-search.component';
|
||||
|
||||
import { SearchFieldComponent } from '../../../../src/app/widgets-common/search-field.component';
|
||||
import { LocationAutocompleteComponent } from '../../../../src/app/widgets-common/location-autocomplete.component';
|
||||
import { LocalNamePipe, LocationIconPipe } from '../../../../src/app/pipes/location.pipes';
|
||||
import { ResourceService } from '../../../../src/app/services/resource.service';
|
||||
import { DefaultService } from '../../../../src/api/api/default.service';
|
||||
@@ -45,6 +46,7 @@ const apidomain = (): { http: string, ws: string } => {
|
||||
declarations: [
|
||||
WeatherSearchComponent,
|
||||
SearchFieldComponent,
|
||||
LocationAutocompleteComponent,
|
||||
LocalNamePipe,
|
||||
LocationIconPipe
|
||||
],
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ export class WeatherSearchComponent implements OnInit {
|
||||
@Input() langCode: 'de' | 'en';
|
||||
@Input() newTab?: boolean;
|
||||
|
||||
navigateFn: (url: string) => any;
|
||||
navigateFn: (location:any, url: string) => any;
|
||||
private readonly baseUrl = 'https://www.mowesta.com/app';
|
||||
|
||||
constructor(private res: ResourceService) { }
|
||||
@@ -24,7 +24,7 @@ export class WeatherSearchComponent implements OnInit {
|
||||
this.res.setLanguage(this.langCode);
|
||||
}
|
||||
const target = this.newTab !== undefined ? '_blank' : '_self';
|
||||
this.navigateFn = (url: string) => window.open(this.baseUrl + url, target);
|
||||
this.navigateFn = (_location, url) => window.open(this.baseUrl + url, target);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,7 +42,8 @@ import { LayoutDrawerComponent, LayoutPlainComponent, DrawerComponent, FooterCom
|
||||
|
||||
import { ToolbarButtonComponent, DecisionPanelComponent, EmailFieldComponent, LanguageSelectComponent,
|
||||
LoginFieldComponent, MapComponent, NameFieldComponent, PasswordFieldComponent, ProfileButtonComponent,
|
||||
SearchFieldComponent, FavoriteButtonComponent, LogoPanelComponent, ClickButtonComponent } from './widgets-common';
|
||||
SearchFieldComponent, FavoriteButtonComponent, LogoPanelComponent, ClickButtonComponent,
|
||||
LocationAutocompleteComponent } from './widgets-common';
|
||||
import { CitiesListComponent, WeatherConditionComponent, WeatherVideoComponent,
|
||||
WeatherVideoBarComponent, WeatherVideoListComponent, WeatherStationsListComponent, WeatherReportsListComponent,
|
||||
WeatherReportComponent, WeatherSummaryComponent, WeatherDiagramComponent } from './widgets-weather';
|
||||
@@ -114,7 +115,7 @@ registerLocaleData(LocaleDE);
|
||||
WeatherPipe, DirectionPipe, SourcePipe, BingMapsPipe, GoogleMapsPipe, WikipediaPipe, LocalTimePipe,
|
||||
LocalDatePipe, LocalNamePipe, LocationIconPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe,
|
||||
WeatherIconPipe, DirectionIconPipe, OsIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe,
|
||||
UseParentFormDirective, ClickButtonComponent, CodeDialogComponent, ConditionMapComponent,
|
||||
UseParentFormDirective, ClickButtonComponent, CodeDialogComponent, ConditionMapComponent, LocationAutocompleteComponent,
|
||||
],
|
||||
imports: [
|
||||
BrowserModule, BrowserAnimationsModule,
|
||||
|
||||
@@ -22,7 +22,7 @@ export class HumidityPipe implements PipeTransform {
|
||||
@Pipe({ name: 'cloud' })
|
||||
export class CloudPipe implements PipeTransform {
|
||||
transform(value: number): string {
|
||||
return (value * 100).toFixed(0) + ' %';
|
||||
return (value * 100).toFixed(2) + ' %';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ export class PressurePipe implements PipeTransform {
|
||||
@Pipe({ name: 'speed' })
|
||||
export class SpeedPipe implements PipeTransform {
|
||||
transform(value: number): string {
|
||||
return (value * 3.6).toFixed(0) + ' km/h / ' + (value * 3.6 * 0.6213711922373339136).toFixed(0) + ' mph';
|
||||
return (value * 3.6).toFixed(0) + ' km/h';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ export class SpeedPipe implements PipeTransform {
|
||||
@Pipe({ name: 'precipitation' })
|
||||
export class PrecipitationPipe implements PipeTransform {
|
||||
transform(value: number): string {
|
||||
return Math.max(0, value).toFixed(1) + ' kg/hm²';
|
||||
return Math.max(0, value).toFixed(1) + ' mm/h';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -141,6 +141,8 @@ export class ResourceService {
|
||||
'search_field_label' : 'Wetter abrufen',
|
||||
'search_field_placeholder' : 'Ortsname',
|
||||
|
||||
'cond_map_search_field_placeholder': 'Ort suchen...',
|
||||
|
||||
'label_city' : 'Stadt',
|
||||
'label_country' : 'Land',
|
||||
'label_state' : 'Region',
|
||||
@@ -581,6 +583,8 @@ export class ResourceService {
|
||||
'search_field_label' : 'Retrieve weather',
|
||||
'search_field_placeholder' : 'Place name',
|
||||
|
||||
'cond_map_search_field_placeholder': 'Search place...',
|
||||
|
||||
'label_city' : 'City',
|
||||
'label_country' : 'Country',
|
||||
'label_state' : 'Region',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { Subscription, BehaviorSubject } from 'rxjs';
|
||||
import { Subscription, BehaviorSubject, concat } from 'rxjs';
|
||||
|
||||
import { ResourceService, CityForecastService, WeatherConditionSummary } from '../services';
|
||||
import { DefaultService, City, Geometry, WeatherCondition,
|
||||
@@ -8,6 +8,7 @@ import { DefaultService, City, Geometry, WeatherCondition,
|
||||
import { CodeDialogComponent } from '../dialogs';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { MapComponentMarker } from "../widgets-common";
|
||||
import { LocalNamePipe } from '../pipes';
|
||||
|
||||
|
||||
@Component({
|
||||
@@ -33,6 +34,7 @@ export class CityComponent implements OnInit, OnDestroy {
|
||||
public readonly res: ResourceService,
|
||||
private readonly apiClientService: DefaultService,
|
||||
private readonly cityForecastService: CityForecastService,
|
||||
private readonly namePipe: LocalNamePipe,
|
||||
private readonly route: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
private dialog: MatDialog
|
||||
@@ -48,10 +50,19 @@ export class CityComponent implements OnInit, OnDestroy {
|
||||
this.forecast.next(null);
|
||||
this.videos.next(null);
|
||||
this.station.next(null);
|
||||
this.markers = [];
|
||||
const cityId = this.city.id;
|
||||
this.apiClientService.getCityBoundary(cityId).subscribe((boundary) => {
|
||||
if (this.city.id === cityId) {
|
||||
this.boundary.next(boundary);
|
||||
if (boundary) {
|
||||
this.boundary.next(boundary);
|
||||
} else {
|
||||
this.markers = this.markers.concat([{
|
||||
coordinate: this.city.coordinate,
|
||||
tooltipOptions: { permanent: false, direction: 'top' },
|
||||
label: this.namePipe.transform(this.city.names)
|
||||
}]);
|
||||
}
|
||||
}
|
||||
});
|
||||
this.apiClientService.getCityCondition(cityId).subscribe((condition) => {
|
||||
@@ -68,13 +79,13 @@ export class CityComponent implements OnInit, OnDestroy {
|
||||
if (this.city.id === cityId) {
|
||||
this.station.next(station);
|
||||
if (station) {
|
||||
this.markers = [{
|
||||
this.markers = this.markers.concat([{
|
||||
coordinate: station.coordinate,
|
||||
label: `${this.res.strings('weather_station_label')}: ${station.name}`,
|
||||
tooltipOptions: { permanent: false, direction: 'top' },
|
||||
iconOptions: { iconUrl: 'assets/icons/icon_sun.png', iconSize: [32, 32] },
|
||||
clicked: () => this.router.navigateByUrl(`/${this.res.getLanguage()}/weather/stations/${station.id}`)
|
||||
}];
|
||||
}]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,25 @@
|
||||
<app-map #appMap [bounds]="initialBounds"
|
||||
<div matAutocompleteOrigin #origin="matAutocompleteOrigin"
|
||||
class="search-container search" tabindex="0"
|
||||
(click)="onSearchClick()" >
|
||||
<mat-icon class="search-icon">search</mat-icon>
|
||||
<input matInput #searchInput class="search-input" type="search"
|
||||
[formControl]="term"
|
||||
[matAutocomplete]="autocomplete"
|
||||
[matAutocompleteConnectedTo]="origin"
|
||||
[placeholder]="res.strings('cond_map_search_field_placeholder')">
|
||||
<mat-progress-spinner *ngIf="!autocompIdle" mode="indeterminate" color="accent" diameter="20"></mat-progress-spinner>
|
||||
</div>
|
||||
<app-location-autocomplete
|
||||
panelWidth="250px"
|
||||
[term]="term"
|
||||
[onLocationSelected]="onLocationSelected"
|
||||
[filterLocationsFn]="filterLocationsFn"
|
||||
(autocompleteInitEvent)="autocomplete = $event"
|
||||
(idleEvent)="autocompIdle = $event">
|
||||
</app-location-autocomplete>
|
||||
<app-map #appMap
|
||||
[bounds]="initialBounds"
|
||||
[maxZoo]="16"
|
||||
[mapEventHandlers]="mapEventHandlers">
|
||||
[mapEventHandlers]="mapEventHandlers"
|
||||
draggable="true">
|
||||
</app-map>
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
|
||||
import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
|
||||
import { FormControl } from "@angular/forms";
|
||||
import { Router } from '@angular/router';
|
||||
import { MatAutocomplete, MatAutocompleteSelectedEvent } from "@angular/material/autocomplete";
|
||||
import { Subscription } from 'rxjs';
|
||||
import { MapComponent } from '../widgets-common';
|
||||
import { ResourceService } from '../services';
|
||||
import { LocalNamePipe, TemperaturePipe, WeatherIconPipe, WeatherPipe } from '../pipes';
|
||||
import { DefaultService } from '../../api/api/default.service';
|
||||
import { City } from '../../api/model/city';
|
||||
import { Coordinate } from '../../api/model/coordinate';
|
||||
import { WeatherForecast } from '../../api/model/weatherForecast';
|
||||
import { City, Coordinate, WeatherForecast, LocationHierarchy } from '../api';
|
||||
import * as L from 'leaflet';
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ class MapTile {
|
||||
/**
|
||||
* A map which is showing small tooltips of cities with some
|
||||
* additional information about the weather condition.
|
||||
* The tooltips are being dynamically reloaded when the user
|
||||
* The tooltips are being dynamically reloaded when the user
|
||||
* moves around or zooms in and out.
|
||||
*
|
||||
* @author Adriano
|
||||
@@ -62,7 +62,30 @@ class MapTile {
|
||||
@Component({
|
||||
selector: 'app-condition-map',
|
||||
templateUrl: './condition-map.component.html',
|
||||
providers: [TemperaturePipe, WeatherIconPipe, WeatherPipe, LocalNamePipe]
|
||||
providers: [TemperaturePipe, WeatherIconPipe, WeatherPipe, LocalNamePipe],
|
||||
styles: [`
|
||||
.search-container { position: absolute; top: 10px; right: 50px; z-index: 10000; }
|
||||
.search {
|
||||
width: 45px;
|
||||
height: 50px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
padding: 10px;
|
||||
background: white;
|
||||
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
|
||||
border-radius: 4px;
|
||||
outline: none;
|
||||
-webkit-transition: width 0.4s ease-in-out;
|
||||
transition: width 0.4s ease-in-out;
|
||||
cursor: pointer;
|
||||
}
|
||||
.search-input { width: 0; font-size: 16px; }
|
||||
.search-icon { font-size: 27px; }
|
||||
.search:focus-within { width: 250px; border: solid 1px #00695c; }
|
||||
.search:focus-within .search-input { width: 100%; }
|
||||
.search:focus-within .search-icon { margin-right: 5px; color: #00695c; }
|
||||
`]
|
||||
})
|
||||
export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
/**
|
||||
@@ -90,12 +113,31 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
{ latitude: -6.1753942, longitude: 106.827183 }, // Jakarta
|
||||
{ latitude: -33.918861, longitude: 18.423300 }, // Kapstadt
|
||||
{ latitude: 68.9791718, longitude: 33.0925102 } // Murmansk
|
||||
// { latitude: 34.052235, longitude: -118.243683 }, // Los Angeles
|
||||
// { latitude: -36.848461, longitude: 174.763336 }, // Auckland
|
||||
];
|
||||
|
||||
@ViewChild('appMap') appMap: MapComponent;
|
||||
@ViewChild('searchInput') searchInput: ElementRef;
|
||||
|
||||
/**
|
||||
* FormControl of the map's search bar.
|
||||
*/
|
||||
term: FormControl;
|
||||
/**
|
||||
* Reference of the MatAutocomplete element to connect to the search bar input.
|
||||
*/
|
||||
autocomplete: MatAutocomplete;
|
||||
/**
|
||||
* Current indicator if the autocomplition is idle or retrieving results from the backend.
|
||||
*/
|
||||
autocompIdle: boolean;
|
||||
/**
|
||||
* Callback for when the user clicks the MatAutocomplete drop down menu.
|
||||
*/
|
||||
onLocationSelected: (event: MatAutocompleteSelectedEvent) => void;
|
||||
/**
|
||||
* Callback to only filter cities in the autocomplete drop down menu.
|
||||
*/
|
||||
filterLocationsFn: (arr: LocationHierarchy[]) => LocationHierarchy[];
|
||||
/**
|
||||
* Registering map event handlers on the leaflet map before initialization.
|
||||
*/
|
||||
@@ -124,9 +166,22 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
* Current zoom level of the map.
|
||||
*/
|
||||
private currZoom = MapComponent.DEFAULT_ZOOM;
|
||||
/**
|
||||
* The position on which the mouse went down on a tooltip.
|
||||
*/
|
||||
private tooltipDownPosition: number[] = [0, 0];
|
||||
/**
|
||||
* The tooltip on which the mouse went down.
|
||||
*/
|
||||
private tooltipDownElement: L.Tooltip = null;
|
||||
/**
|
||||
* The slop which we allow until we start ignoring touch events.
|
||||
* This is a number of pixels squared (i.e. 400 = 20px).
|
||||
*/
|
||||
private readonly tooltipDownSlop = 400;
|
||||
|
||||
constructor(
|
||||
private readonly res: ResourceService,
|
||||
public readonly res: ResourceService,
|
||||
private readonly defaultService: DefaultService,
|
||||
private readonly router: Router,
|
||||
private readonly temperaturePipe: TemperaturePipe,
|
||||
@@ -136,6 +191,8 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.term = new FormControl('');
|
||||
this.autocompIdle = true;
|
||||
this.pendingMapTiles = new Map<string, MapTile>();
|
||||
this.cachedMapTiles = new Map<string, MapTile>();
|
||||
this.cachedCityData = new Map<number, CityData>();
|
||||
@@ -147,12 +204,27 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
zoomend: e => this.onZoomLevelChanged(e.target._zoom),
|
||||
moveend: _ => this.onViewportChanged()
|
||||
};
|
||||
this.filterLocationsFn = arr => arr.filter(v => v.type === LocationHierarchy.TypeEnum.CITY);
|
||||
this.onLocationSelected = (event: MatAutocompleteSelectedEvent) => {
|
||||
this.term.setValue('');
|
||||
if (event.option?.value) {
|
||||
const location = event.option.value as LocationHierarchy;
|
||||
this.appMap.map.setView([location.coordinate.latitude, location.coordinate.longitude], 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
this.appMap.map.setMinZoom(3);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets focus on the inner input element.
|
||||
*/
|
||||
onSearchClick(): void {
|
||||
this.searchInput.nativeElement.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called only when the map is loaded for the first time and the 'zoomend' event is triggered.
|
||||
*
|
||||
@@ -331,7 +403,7 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the whole line of tiles is at least 75% within the viewport.
|
||||
* Checks if the whole line of tiles is at least 10% within the viewport.
|
||||
* Only the outer tiles of the map are checked.
|
||||
*
|
||||
* @param boundary The boundary to check. (North, East, South, West)
|
||||
@@ -339,7 +411,7 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
* @param cornerOutVp The corner of the tile not within the viewport.
|
||||
*/
|
||||
private isTileLineInViewPort(boundary: number, cornerOnVp: number, cornerOutVp: number): number {
|
||||
return ((Math.abs(cornerOnVp - boundary) / Math.abs(cornerOnVp - cornerOutVp)) >= 0.75) ? 0 : 1;
|
||||
return ((Math.abs(cornerOnVp - boundary) / Math.abs(cornerOnVp - cornerOutVp)) >= 0.10) ? 0 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -370,7 +442,7 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
|
||||
// Check if the tooltip is outside the tile boundaries and correct if necessary.
|
||||
// Need to invert the offset because -offset[0]/-offset[1] is incrementing the x/y
|
||||
// instead of decrementing as expected.
|
||||
// from the tooltip center instead of decrementing it as usually expected.
|
||||
const topEdge = cityCoord.y - offset[1] + 34, rightEdge = cityCoord.x - offset[0] + 100,
|
||||
bottomEdge = cityCoord.y - offset[1] - 32, leftEdge = cityCoord.x - offset[0] - 100;
|
||||
if (leftEdge < NWLayerPoint.x) {
|
||||
@@ -433,8 +505,25 @@ export class ConditionMapComponent implements OnInit, AfterViewInit {
|
||||
.setContent(content)
|
||||
.setLatLng(new L.LatLng(cityData.city.coordinate.latitude, cityData.city.coordinate.longitude))
|
||||
.addTo(this.appMap.map);
|
||||
cityData.tooltip.getElement().addEventListener('click', ev => {
|
||||
this.router.navigateByUrl(`/${this.res.getLanguage()}/weather/cities/${cityData.city.id}`);
|
||||
// this used to be a click handler, but unfortunately, the click
|
||||
// will also be issued if the map is dragged which creates a user
|
||||
// experience that really stinks, so we need to run our own click
|
||||
// detection code that ignores clicks where up and down are not
|
||||
// on the same location (because the user dragged the map)
|
||||
cityData.tooltip.getElement().addEventListener('mousedown', ev => {
|
||||
this.tooltipDownElement = cityData.tooltip;
|
||||
this.tooltipDownPosition = [ev.clientX, ev.clientY ];
|
||||
});
|
||||
cityData.tooltip.getElement().addEventListener('mouseup', ev => {
|
||||
if (this.tooltipDownElement === cityData.tooltip) {
|
||||
const dx = this.tooltipDownPosition[0] - ev.clientX;
|
||||
const dy = this.tooltipDownPosition[1] - ev.clientY;
|
||||
if (dx * dx + dy * dy < this.tooltipDownSlop) {
|
||||
this.router.navigateByUrl(`/${this.res.getLanguage()}/weather/cities/${cityData.city.id}`);
|
||||
}
|
||||
}
|
||||
this.tooltipDownElement = null;
|
||||
this.tooltipDownPosition = [0, 0];
|
||||
});
|
||||
cityData.tooltip.getElement().style.pointerEvents = 'auto';
|
||||
cityData.tooltip.getElement().style.cursor = 'pointer';
|
||||
|
||||
@@ -12,3 +12,4 @@ export * from './toolbar-button.component';
|
||||
export * from './favorite-button.component';
|
||||
export * from './logo-panel.component';
|
||||
export * from './click-button.component';
|
||||
export * from './location-autocomplete.component';
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<mat-autocomplete #auto="matAutocomplete" [panelWidth]="panelWidth" autoActiveFirstOption (optionSelected)="onLocationSelected($event);">
|
||||
<mat-option style="padding-left: 3px; padding-right: 3px;" *ngFor="let option of locations; let i = index" [value]="option" [id]="i">
|
||||
<div class="fx-row" style="justify-content: start; align-items: center;">
|
||||
<mat-icon style="margin-right: 4px;">{{ option.type | locationIcon }}</mat-icon>
|
||||
<div class="fx-column">
|
||||
<div class="m-z p-z ellipsis" style="font-size: 14px; line-height: 16px; width: 162px;">{{ option.names | localName }}</div>
|
||||
<div class="m-z p-z ellipsis" style="font-size: 10px; line-height: 12px; width: 162px;">
|
||||
<span *ngIf="option.parent">
|
||||
{{ option.parent.names | localName:true }}
|
||||
<span *ngIf="option.parent.parent">, {{ option.parent.parent.names | localName:true }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mat-option>
|
||||
</mat-autocomplete>
|
||||
@@ -0,0 +1,106 @@
|
||||
import { AfterViewInit, Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
|
||||
import { FormControl } from "@angular/forms";
|
||||
import { MatAutocomplete, MatAutocompleteSelectedEvent } from "@angular/material/autocomplete";
|
||||
import { Subscription } from "rxjs";
|
||||
import { ResourceService } from "../services";
|
||||
import { DefaultService, LocationHierarchy } from "../api";
|
||||
|
||||
/**
|
||||
* Autocomplete drop down menu which can be re-used for custom MatInput components.
|
||||
* It displays dynamically location names while the user is entering information
|
||||
* into the MatInput this component is connected to.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-location-autocomplete',
|
||||
templateUrl: './location-autocomplete.component.html'
|
||||
})
|
||||
export class LocationAutocompleteComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
/**
|
||||
* Term which is detected for changes. Mandatory.
|
||||
*/
|
||||
@Input() term: FormControl;
|
||||
/**
|
||||
* Specifies the width of the drop down menu.
|
||||
*/
|
||||
@Input() panelWidth: string;
|
||||
/**
|
||||
* Callback function which is called when user is selecting an option from the drop down menu. Mandatory.
|
||||
*/
|
||||
@Input() onLocationSelected: (event: MatAutocompleteSelectedEvent) => void;
|
||||
/**
|
||||
* Optional filter function to filter the LocationHierarchy results to be displayed in the drop down menu.
|
||||
* If omitted this function is initialized to return the given array.
|
||||
*/
|
||||
@Input() filterLocationsFn: (arr: LocationHierarchy[]) => LocationHierarchy[];
|
||||
/**
|
||||
* Event which is fired after the MatAutocomplete view element is initialized. Sends a reference of the
|
||||
* MatAutocomplete view element to the parent to be plugged into the corresponding MatInput element.
|
||||
*/
|
||||
@Output() autocompleteInitEvent = new EventEmitter<MatAutocomplete>();
|
||||
/**
|
||||
* Event which emits current state of the autocompletion. Can be used for progress bar animations.
|
||||
*/
|
||||
@Output() idleEvent = new EventEmitter<boolean>();
|
||||
|
||||
@ViewChild('auto') autocompleteRef: MatAutocomplete;
|
||||
|
||||
locations: LocationHierarchy[];
|
||||
private requestId: number;
|
||||
private idle: boolean;
|
||||
private subscription: Subscription;
|
||||
|
||||
constructor(public res: ResourceService, private apiClientService: DefaultService) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
if (!this.term) { new Error('Input term must not be empty!') }
|
||||
if (!this.onLocationSelected) { new Error('Input onLocationSelected must not be empty!') }
|
||||
if (!this.filterLocationsFn) { this.filterLocationsFn = arr => arr; }
|
||||
if (!this.panelWidth) { this.panelWidth = '220px'; }
|
||||
this.locations = [];
|
||||
this.requestId = 0;
|
||||
this.setIdle(true);
|
||||
this.subscription = this.term.valueChanges.subscribe(() => {
|
||||
this.setIdle(false);
|
||||
const value = this.term.value;
|
||||
const id = ++this.requestId;
|
||||
this.locations = [];
|
||||
if (value.length > 0) {
|
||||
setTimeout(() => {
|
||||
if (this.requestId === id) {
|
||||
this.apiClientService.searchLocations(this.res.getLanguage(), value, 0, 20, null)
|
||||
.subscribe({
|
||||
next: page => {
|
||||
if (id === this.requestId) {
|
||||
this.locations = this.filterLocationsFn(page.elements);
|
||||
this.setIdle(true);
|
||||
}
|
||||
},
|
||||
error: _ => {
|
||||
if (id === this.requestId) {
|
||||
this.setIdle(true)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}, 250);
|
||||
} else {
|
||||
this.setIdle(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
// Needs to be put onto the event queue or else the change detection will throw the
|
||||
// nasty ExpressionChangedAfterItHasBeenCheckedError while in the debug mode.
|
||||
setTimeout(() => this.autocompleteInitEvent.emit(this.autocompleteRef));
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscription.unsubscribe();
|
||||
}
|
||||
|
||||
private setIdle(val: boolean): void {
|
||||
this.idle = val;
|
||||
this.idleEvent.emit(val);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export class MapComponent implements OnInit, DoCheck {
|
||||
@Input() coordinate: Coordinate;
|
||||
@Input() zoom: number;
|
||||
@Input() maxZoo: number;
|
||||
@Input() draggable: boolean;
|
||||
@Input() bounds: Coordinate[];
|
||||
@Input() boundary: Geometry;
|
||||
@Input() markers: MapComponentMarker[];
|
||||
@@ -58,8 +59,10 @@ export class MapComponent implements OnInit, DoCheck {
|
||||
ngOnInit() {
|
||||
const object = this;
|
||||
this.map = new L.Map(this.mapElement.nativeElement, {
|
||||
attributionControl: false, zoomControl: false,
|
||||
dragging: !L.Browser.mobile, tap: !L.Browser.mobile,
|
||||
attributionControl: false,
|
||||
zoomControl: false,
|
||||
dragging: (L.Browser.mobile && this.draggable) ? true : !L.Browser.mobile,
|
||||
tap: !L.Browser.mobile,
|
||||
minZoom: 1,
|
||||
maxZoom: 15,
|
||||
maxBounds: [[-90, -180],[90, 180]]
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
<div class="fx-row fx-auto">
|
||||
<div class="fx-row fx-auto">
|
||||
<mat-form-field style="font-size: small; width: 220px;">
|
||||
<mat-label>{{ res.strings('search_field_label') }}</mat-label>
|
||||
<input matInput type="search" [formControl]="term" [matAutocomplete]="auto" [placeholder]="res.strings('search_field_placeholder')">
|
||||
<input matInput type="search"
|
||||
[formControl]="term"
|
||||
[matAutocomplete]="autocomplete"
|
||||
[placeholder]="res.strings('search_field_placeholder')" >
|
||||
<mat-icon *ngIf="idle; else searching" matSuffix>search</mat-icon>
|
||||
<ng-template #searching><mat-progress-spinner matSuffix mode="indeterminate" color="accent" diameter="20"></mat-progress-spinner></ng-template>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-autocomplete #auto="matAutocomplete" panelWidth="220px" autoActiveFirstOption (optionSelected)="onLocationSelected($event);">
|
||||
<mat-option style="padding-left: 3px; padding-right: 3px;" *ngFor="let option of locations; let i = index" [value]="option" [id]="i">
|
||||
<div class="fx-row" style="justify-content: start; align-items: center;">
|
||||
<mat-icon style="margin-right: 4px;">{{ option.type | locationIcon }}</mat-icon>
|
||||
<div class="fx-column">
|
||||
<div class="m-z p-z ellipsis" style="font-size: 14px; line-height: 16px; width: 162px;">{{ option.names | localName }}</div>
|
||||
<div class="m-z p-z ellipsis" style="font-size: 10px; line-height: 12px; width: 162px;">
|
||||
<span *ngIf="option.parent">{{ option.parent.names | localName:true }}<span *ngIf="option.parent.parent">, {{ option.parent.parent.names | localName:true }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</mat-option>
|
||||
</mat-autocomplete>
|
||||
|
||||
<app-location-autocomplete
|
||||
[term]="term"
|
||||
[onLocationSelected]="onLocationSelected"
|
||||
(autocompleteInitEvent)="autocomplete = $event"
|
||||
(idleEvent)="idle = $event">
|
||||
</app-location-autocomplete>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
|
||||
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
|
||||
import { Component, OnInit, Input } from '@angular/core';
|
||||
import { MatAutocomplete, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
|
||||
import { Router } from '@angular/router';
|
||||
import { FormControl } from '@angular/forms';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { DefaultService, LocationHierarchy } from '../api';
|
||||
import { LocationHierarchy } from '../api';
|
||||
import { ResourceService } from '../services';
|
||||
|
||||
/**
|
||||
@@ -14,68 +13,37 @@ import { ResourceService } from '../services';
|
||||
templateUrl: './search-field.component.html',
|
||||
styles: [ '.mat-input-element::placeholder { color: white; opacity: 0.75; }']
|
||||
})
|
||||
export class SearchFieldComponent implements OnInit, OnDestroy {
|
||||
/**
|
||||
* Specifies the navigate function that should be used.
|
||||
* Used for the web component implementation.
|
||||
*/
|
||||
@Input() navigateFn: (url: string) => any;
|
||||
export class SearchFieldComponent implements OnInit {
|
||||
/**
|
||||
* Specifies the navigate function that should be used.
|
||||
* Used for the web component implementation.
|
||||
*/
|
||||
@Input() navigateFn: (location: LocationHierarchy, url: string) => any;
|
||||
|
||||
term = new FormControl('');
|
||||
locations: LocationHierarchy[] = [];
|
||||
subscription: Subscription;
|
||||
requestId = 0;
|
||||
idle = true;
|
||||
autocomplete: MatAutocomplete;
|
||||
term = new FormControl('');
|
||||
idle = true;
|
||||
onLocationSelected: (MatAutocompleteSelectedEvent) => void;
|
||||
|
||||
constructor(private router: Router, public res: ResourceService, private apiClientService: DefaultService) { }
|
||||
constructor(private router: Router, public res: ResourceService) { }
|
||||
|
||||
ngOnInit() {
|
||||
if (!this.navigateFn) {
|
||||
this.navigateFn = (url: string) => this.router.navigateByUrl(url);
|
||||
}
|
||||
this.subscription = this.term.valueChanges.subscribe(() => {
|
||||
this.idle = false;
|
||||
const value = this.term.value;
|
||||
const id = ++this.requestId;
|
||||
this.locations = [];
|
||||
if (value.length > 0) {
|
||||
setTimeout(() => {
|
||||
if (this.requestId === id) {
|
||||
this.apiClientService.searchLocations(this.res.getLanguage(), value, 0, 20, null).subscribe((page) => {
|
||||
if (id === this.requestId) {
|
||||
this.locations = page.elements;
|
||||
this.idle = true;
|
||||
}
|
||||
}, (error) => {
|
||||
if (id === this.requestId) {
|
||||
this.idle = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, 250);
|
||||
} else {
|
||||
this.idle = true;
|
||||
}
|
||||
});
|
||||
ngOnInit() {
|
||||
if (!this.navigateFn) {
|
||||
this.navigateFn = (_location, url) => this.router.navigateByUrl(url);
|
||||
}
|
||||
|
||||
onLocationSelected(event: MatAutocompleteSelectedEvent): void {
|
||||
this.term.setValue('');
|
||||
let url = '/' + this.res.getLanguage() + '/weather/';
|
||||
switch (event.option.value.type) {
|
||||
case LocationHierarchy.TypeEnum.CITY:
|
||||
url += 'cities'; break;
|
||||
case LocationHierarchy.TypeEnum.COUNTRY:
|
||||
url += 'countries'; break;
|
||||
case LocationHierarchy.TypeEnum.STATE:
|
||||
url += 'states'; break;
|
||||
}
|
||||
url += '/' + event.option.value.id;
|
||||
this.navigateFn(url);
|
||||
this.onLocationSelected = (event: MatAutocompleteSelectedEvent) => {
|
||||
this.term.setValue('');
|
||||
let url = '/' + this.res.getLanguage() + '/weather/';
|
||||
switch (event.option.value.type) {
|
||||
case LocationHierarchy.TypeEnum.CITY:
|
||||
url += 'cities'; break;
|
||||
case LocationHierarchy.TypeEnum.COUNTRY:
|
||||
url += 'countries'; break;
|
||||
case LocationHierarchy.TypeEnum.STATE:
|
||||
url += 'states'; break;
|
||||
}
|
||||
url += '/' + event.option.value.id;
|
||||
this.navigateFn(event.option.value, url);
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.subscription.unsubscribe();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user