optimization of the detection algorithem.

BOOK update.
This commit is contained in:
Jan Pleterski
2026-11-27 09:43:25 +01:00
parent b22d7987e3
commit 5f9e2a3b86
11 changed files with 1209 additions and 542 deletions
+477 -216
View File
@@ -12,13 +12,20 @@ import '../widgets/section.dart';
import 'session_screen.dart';
import 'target_view.dart';
enum _View { stats, history }
enum _Filter { training, tournament }
enum _HistoryFilter { all, training, tournament }
enum _Period { month, threeMonths, year, all, custom }
/// Knjiga: one summary card with the shooter's form, records and progress graph,
/// then their sessions. One period filter drives the card and the list, so they
/// always agree; the graph has its own month/year navigation.
/// Knjiga, two screens:
/// * Statistika: the summary card (form, records) and the progress graph for
/// one kind of session and one number of shots per target, so averages
/// compare like with like. The graph has its own month/year navigation.
/// * Zgodovina: every session of the chosen kind, whatever its shot count.
/// One period filter drives the card and the list, so they always agree.
class BookScreen extends StatefulWidget {
const BookScreen({super.key});
@@ -31,7 +38,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
List<Session>? _sessions; // all sessions; null while loading
List<int> _years = []; // years with sessions, newest first
_Filter _filter = _Filter.training;
_View _view = _View.stats;
_Filter _filter = _Filter.training; // Statistika: trainings or tournaments
_HistoryFilter _historyFilter = _HistoryFilter.all; // Zgodovina
int? _shots; // shots per target shown; null = pick the most common one
bool _sortByScore = false;
_Period _period = _Period.year;
@@ -63,7 +72,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
final end = p.getInt('${_prefix}customEnd');
if (!mounted) return;
setState(() {
_view = pick(_View.values, 'view', _view);
_filter = pick(_Filter.values, 'filter', _filter);
_historyFilter = pick(_HistoryFilter.values, 'historyFilter', _historyFilter);
_period = pick(_Period.values, 'period', _period);
_shots = p.getInt('${_prefix}shots');
_sortByScore = p.getBool('${_prefix}sortByScore') ?? _sortByScore;
@@ -80,7 +91,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
Future<void> _saveSettings() async {
final p = await SharedPreferences.getInstance();
await p.setInt('${_prefix}view', _view.index);
await p.setInt('${_prefix}filter', _filter.index);
await p.setInt('${_prefix}historyFilter', _historyFilter.index);
await p.setInt('${_prefix}period', _period.index);
if (_shots == null) {
await p.remove('${_prefix}shots');
@@ -262,8 +275,17 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
]);
}
// Statistics only compare like with like: one tab, one shots-per-target
// format. The card and the list use the period; the graph its own month/year.
if (_view == _View.history) {
return Column(children: [
_buildTabs(),
_buildHistoryBar(),
Expanded(child: _buildHistoryScreen()),
]);
}
// Statistics only compare like with like: one kind of session, one
// shots-per-target format. The card uses the period; the graph its own
// month/year.
final typed = _filtered;
final formats = _formats(typed.where(_inPeriod).toList());
final shots = formats.contains(_shots)
@@ -280,23 +302,18 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
return Column(
children: [
_buildTabs(),
_buildFilterBar(formats, shots),
_buildStatsBar(formats, shots),
Expanded(
child: RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
children: [
if (_years.isEmpty)
_buildEmpty()
else ...[
if (stats.targets > 0) _buildSummary(format, stats),
..._buildHistory(sessions,
stats.sessions > 1 ? stats.averagePerShot : null),
],
],
),
),
child: _years.isEmpty
? _centered(_buildEmpty())
: stats.targets == 0
? Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: _periodRow()),
Expanded(child: _centered(_noSessions())),
])
: _buildStats(format, stats),
),
],
);
@@ -304,43 +321,205 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
);
}
// Filters continue the dark app bar, like Koledar/Stiki
// An empty state in the middle of the free space; pull-to-refresh still works
Widget _centered(Widget child) {
return RefreshIndicator(
onRefresh: _load,
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: child,
),
),
),
],
),
);
}
// Nothing in the chosen period or filter (there are sessions elsewhere)
Widget _noSessions() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.only(bottom: 48), // a little above the middle
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.event_busy_rounded, size: 40, color: surf.textSecondary),
const SizedBox(height: 10),
Text(s.t('No sessions in this period'),
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15, color: surf.textSecondary)),
],
),
);
}
// Full-width "Obdobje … To leto ▾" button: says what it changes and that it
// can be tapped. Opens the period sheet; Statistika and Zgodovina share it.
Widget _periodRow() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Material(
color: surf.card,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _pickPeriod,
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
child: Row(
children: [
Icon(Icons.date_range_rounded, size: 20, color: s.bulletColor),
const SizedBox(width: 10),
Text(s.t('Period'),
style: TextStyle(fontSize: 13, color: surf.textSecondary)),
const SizedBox(width: 12),
Expanded(
child: Text(
_periodLabel(_period),
textAlign: TextAlign.right,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: surf.textPrimary),
),
),
Icon(Icons.expand_more_rounded, color: surf.textSecondary),
],
),
),
),
);
}
// Zgodovina: every session of the chosen kind in the period, any shot count
Widget _buildHistoryScreen() {
if (_years.isEmpty) return _centered(_buildEmpty());
final sessions = [
for (final x in _sessions!)
if (_inPeriod(x) &&
switch (_historyFilter) {
_HistoryFilter.all => true,
_HistoryFilter.training => !x.isTournament,
_HistoryFilter.tournament => x.isTournament,
})
x,
];
// Average per shot over the listed sessions, for each card's difference
final shots = sessions.fold(0, (a, x) => a + x.shots);
final average = sessions.length > 1 && shots > 0
? sessions.fold(0, (a, x) => a + x.totalScore) / shots
: null;
if (sessions.isEmpty) {
return Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: _historyHeader()),
Expanded(child: _centered(_noSessions())),
]);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 32),
children: _buildHistory(sessions, average),
),
);
}
// The two screens; filters continue the dark app bar, like Koledar/Stiki
Widget _buildTabs() {
final s = AppSettings.instance;
return BarTabs(
tabs: [
BarTab(s.t('Trainings'), Icons.track_changes_rounded),
BarTab(s.t('Tournaments'), Icons.emoji_events_rounded),
BarTab(s.t('Statistics'), Icons.insights_rounded),
BarTab(s.t('History'), Icons.history_rounded),
],
selected: _filter.index,
onSelect: (i) => _change(() {
_filter = _Filter.values[i];
_shots = null;
_chartAt = null;
}),
selected: _view.index,
onSelect: (i) => _change(() => _view = _View.values[i]),
);
}
// Second dark row under the tabs: shots-per-target pills across the width
// Always 1–5 (the capture limit); older saves above 5 keep their own pill.
// Formats with no targets yet are dimmed and can't be picked.
Widget _buildFilterBar(List<int> formats, int? selected) {
// Zgodovina's dark row: which sessions to list
Widget _buildHistoryBar() {
final s = AppSettings.instance;
final labels = {
_HistoryFilter.all: s.t('All'),
_HistoryFilter.training: s.t('Trainings'),
_HistoryFilter.tournament: s.t('Tournaments'),
};
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
child: Row(
children: [
for (final f in _HistoryFilter.values) ...[
if (f.index > 0) const SizedBox(width: 6),
Expanded(
child: _BarPill(
label: labels[f]!,
selected: f == _historyFilter,
empty: false,
onTap: () => _change(() => _historyFilter = f),
),
),
],
],
),
);
}
// Statistika's dark row: trainings or tournaments, then shots per target.
// Shots are always 1–5 (the capture limit); older saves above 5 keep their
// own pill. Formats with no targets yet are dimmed and can't be picked.
Widget _buildStatsBar(List<int> formats, int? selected) {
final s = AppSettings.instance;
final sorted = {
for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n,
...formats,
}.toList()
..sort();
Widget kind(_Filter f, String label) => Expanded(
flex: 5,
child: _BarPill(
label: s.t(label),
selected: f == _filter,
empty: false,
onTap: () => _change(() {
_filter = f;
_shots = null;
_chartAt = null;
}),
),
);
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
// Pills share the full width equally
child: Row(
children: [
Text(AppSettings.instance.t('Shots'),
style: const TextStyle(fontSize: 12, color: Colors.white60)),
kind(_Filter.training, 'Trainings'),
const SizedBox(width: 6),
kind(_Filter.tournament, 'Tournaments'),
// Divider between the two groups
Container(
width: 1,
height: 22,
margin: const EdgeInsets.symmetric(horizontal: 8),
color: Colors.white24),
for (final n in sorted) ...[
const SizedBox(width: 6),
if (n != sorted.first) const SizedBox(width: 4),
Expanded(
flex: 2,
child: _BarPill(
label: '$n',
selected: n == selected,
@@ -355,6 +534,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
);
}
// Monday–Sunday week of [date], cut to its month: "6.–12. 10.", "27.–31. 10."
static String _weekLabel(DateTime date) {
final day = DateTime(date.year, date.month, date.day);
@@ -427,105 +607,143 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
s.isLightBackground ? Colors.black : Colors.white, amount)!;
}
// Hero on the card surface (follows light/dark like the rest of Knjiga): the
// period's average per shot with its trend, counts and best session.
// The graph below gets every loaded session of the format, [all], and picks
// its own month or year.
Widget _buildSummary(List<Session> all, ShooterStats stats) {
// Statistika as cards: one with the period's average per shot and its trend
// beside three counts; the graph; the best session. It fits
// the screen without scrolling, the graph taking the height that is left;
// on a screen too small for that it scrolls with a fixed-height graph.
// The graph gets every loaded session of the format, [all], and picks its
// own month or year.
Widget _buildStats(List<Session> all, ShooterStats stats) {
final s = AppSettings.instance;
final bestSession = stats.bestSession;
final tournaments = _filter == _Filter.tournament;
const gap = SizedBox(height: 12);
// One card: the average on the left, the three counts on the right
final surf = Surfaces.current;
final top = _BookCard(
padding: const EdgeInsets.symmetric(vertical: 14),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(flex: 11, child: _averageContent(stats)),
VerticalDivider(width: 1, thickness: 1, color: surf.divider),
Expanded(
flex: 9,
child: Padding(
padding: const EdgeInsets.only(left: 14, right: 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_CountLine(
value: '${stats.sessions}',
label: s.t(tournaments ? 'Tournaments' : 'Trainings')),
_CountLine(
value: '${stats.targets}', label: s.t('Targets')),
_CountLine(
value: stats.averageTarget!.toStringAsFixed(1),
label: s.t('Average target')),
],
),
),
),
],
),
),
);
// Best session; tap to see its targets
final best = bestSession != null && stats.sessions > 1
? _HeroRecord(
label: s.t(tournaments ? 'Best tournament' : 'Best training'),
value: bestSession.averagePerShot!.toStringAsFixed(2),
caption:
'${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}',
onTap: () => _openTargets(bestSession),
)
: null;
return LayoutBuilder(builder: (context, box) {
// Room for the cards above plus a graph that is still worth reading
if (box.maxHeight >= 560) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(
children: [
_periodRow(),
const SizedBox(height: 8),
top,
gap,
Expanded(child: _BookCard(child: _buildChart(all, stats, fill: true))),
if (best != null) ...[gap, best],
],
),
);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
children: [
_periodRow(),
const SizedBox(height: 8),
top,
gap,
_BookCard(child: _buildChart(all, stats)),
if (best != null) ...[gap, best],
],
),
);
});
}
Widget _averageContent(ShooterStats stats) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final trend = stats.trend;
final bestSession = stats.bestSession;
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: ColoredBox(
color: surf.card,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(18, 16, 18, 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(s.t('Average per shot').toUpperCase(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
letterSpacing: 1.2,
color: surf.textSecondary)),
Text(
stats.averagePerShot?.toStringAsFixed(2) ?? '–',
style: TextStyle(
fontSize: 44,
fontWeight: FontWeight.w800,
color: surf.textPrimary,
height: 1.1),
),
if (trend != null)
Text(
'${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _deltaColor(trend)),
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_HeroCount(
value: '${stats.sessions}',
label: s.t(_filter == _Filter.tournament
? 'Tournaments'
: 'Trainings')),
_HeroCount(
value: '${stats.targets}', label: s.t('Targets')),
_HeroCount(
value: stats.averageTarget!.toStringAsFixed(1),
label: s.t('Average target')),
],
),
],
),
// Best session; tap to see its targets
if (bestSession != null && stats.sessions > 1) ...[
const SizedBox(height: 14),
_HeroRecord(
label: s.t(_filter == _Filter.tournament
? 'Best tournament'
: 'Best training'),
value: bestSession.averagePerShot!.toStringAsFixed(2),
caption:
'${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}',
onTap: () => _openTargets(bestSession),
),
],
],
),
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(s.t('Average per shot').toUpperCase(),
maxLines: 2,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
letterSpacing: 1.2,
color: surf.textSecondary)),
FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
stats.averagePerShot?.toStringAsFixed(2) ?? '–',
style: TextStyle(
fontSize: 48,
fontWeight: FontWeight.w800,
color: surf.textPrimary,
height: 1.1),
),
Divider(height: 1, thickness: 1, color: surf.divider),
_buildChart(all, stats),
],
),
),
if (trend != null)
Text(
'${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: _deltaColor(trend)),
),
],
),
);
}
// Shot average and points per session, each on its own scale.
Widget _buildChart(List<Session> all, ShooterStats stats) {
// [fill]: the graph takes all the height the card gets (inside an Expanded)
Widget _buildChart(List<Session> all, ShooterStats stats, {bool fill = false}) {
final s = AppSettings.instance;
final surf = Surfaces.current;
final scored = all.where((x) => x.shots > 0).toList();
@@ -594,23 +812,32 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
],
),
if (shown.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
child: Text(s.t('No sessions in this period'),
style: TextStyle(color: surf.textSecondary)),
_fillIf(
fill,
Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
child: Center(
child: Text(s.t('No sessions in this period'),
style: TextStyle(color: surf.textSecondary)),
),
),
)
else ...[
const SizedBox(height: 4),
ProgressChart(
labels: data.labels,
series: [
ChartSeries(s.t('Shot average'), s.bulletColor, data.perShot,
axis: ChartAxis.left),
ChartSeries(s.t('Number of points'), _tint(0.55), data.total,
decimals: 0, axis: ChartAxis.right),
],
textColor: surf.textSecondary,
gridColor: surf.divider,
_fillIf(
fill,
ProgressChart(
expand: fill,
labels: data.labels,
series: [
ChartSeries(s.t('Shot average'), s.bulletColor, data.perShot,
axis: ChartAxis.left),
ChartSeries(s.t('Number of points'), _tint(0.55), data.total,
decimals: 0, axis: ChartAxis.right),
],
textColor: surf.textSecondary,
gridColor: surf.divider,
),
),
],
],
@@ -618,6 +845,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
);
}
static Widget _fillIf(bool fill, Widget child) =>
fill ? Expanded(child: child) : child;
List<Widget> _buildHistory(List<Session> sessions, double? average) {
// Average per shot, so sessions with more targets don't win by volume
final ordered = _sortByScore
@@ -627,59 +857,53 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
return [
_historyHeader(),
for (final x in ordered) _sessionCard(x, average),
if (sessions.isEmpty)
Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(AppSettings.instance.t('No sessions in this period'),
style: TextStyle(color: Surfaces.current.textSecondary)),
),
),
];
}
// Section title, then the period chip (drives the card above too) and the sort toggle
// Period selector (shared with Statistika) and the sort order, both labelled
Widget _historyHeader() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 12, 0, 4),
child: Row(
// With the list's 4 px this starts 8 px under the bar, like Statistika
padding: const EdgeInsets.only(top: 4, bottom: 8),
// Same height for both buttons
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Text(
s.t(_sortByScore ? 'Best results' : 'History').toUpperCase(),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
letterSpacing: 1.4,
color: surf.textSecondary,
Expanded(child: _periodRow()),
const SizedBox(width: 8),
// Each tap switches between date and score order
Material(
color: surf.card,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _change(() => _sortByScore = !_sortByScore),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
Icon(
_sortByScore
? Icons.leaderboard_rounded
: Icons.event_rounded,
size: 20,
color: s.bulletColor),
const SizedBox(width: 6),
Text(s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: surf.textPrimary)),
],
),
),
),
),
ActionChip(
avatar: Icon(Icons.date_range_rounded,
size: 16, color: surf.textSecondary),
label: Text(_periodLabel(_period)),
labelStyle: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: surf.textPrimary),
backgroundColor: surf.card,
side: BorderSide.none,
shape: const StadiumBorder(),
visualDensity: VisualDensity.compact,
onPressed: _pickPeriod,
),
// Each tap switches between date and score order
IconButton(
tooltip: s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
icon: Icon(
_sortByScore ? Icons.leaderboard_rounded : Icons.event_rounded,
color: surf.textSecondary),
onPressed: () => _change(() => _sortByScore = !_sortByScore),
),
],
),
),
);
}
@@ -789,14 +1013,24 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Container(
padding: const EdgeInsets.symmetric(vertical: 48, horizontal: 24),
width: double.infinity,
margin: const EdgeInsets.only(bottom: 48), // a little above the middle
padding: const EdgeInsets.symmetric(vertical: 36, horizontal: 24),
decoration: BoxDecoration(
color: surf.card, borderRadius: BorderRadius.circular(20)),
color: surf.card, borderRadius: BorderRadius.circular(24)),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.track_changes_rounded,
size: 48, color: surf.textSecondary),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: s.bulletColor.withValues(alpha: 0.15),
shape: BoxShape.circle,
),
child: Icon(Icons.track_changes_rounded,
size: 44, color: s.bulletColor),
),
const SizedBox(height: 16),
Text(
s.t('No saved target data found'),
textAlign: TextAlign.center,
@@ -821,6 +1055,10 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
void showBookHelp(BuildContext context) {
final s = AppSettings.instance;
showHelpSheet(context, accent: s.bulletColor, t: s.t, items: const [
(
Icons.insights_rounded,
'Statistics / History: your form and progress graph, or the list of all your sessions.'
),
(
Icons.emoji_events_rounded,
'Trainings / Tournaments: choose which sessions the statistics count.'
@@ -843,7 +1081,11 @@ void showBookHelp(BuildContext context) {
),
(
Icons.date_range_rounded,
'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.'
'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.'
),
(
Icons.filter_list_rounded,
'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.'
),
(
Icons.sort_rounded,
@@ -851,7 +1093,7 @@ void showBookHelp(BuildContext context) {
),
(
Icons.touch_app_rounded,
'Tap a session to see all its targets with the selected number of shots on one target.'
'Tap a session to see all its targets on one target.'
),
(
Icons.more_vert_rounded,
@@ -860,36 +1102,55 @@ void showBookHelp(BuildContext context) {
]);
}
/// "12 Trainings" line on the hero, value first.
class _HeroCount extends StatelessWidget {
final String value;
final String label;
/// A rounded card on the page, the same surface as the history cards.
class _BookCard extends StatelessWidget {
final Widget child;
final EdgeInsetsGeometry padding;
const _HeroCount({required this.value, required this.label});
const _BookCard({required this.child, this.padding = EdgeInsets.zero});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.only(top: 2),
child: Text.rich(
TextSpan(children: [
TextSpan(
text: value,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
TextSpan(
text: ' $label',
style: TextStyle(fontSize: 12, color: surf.textSecondary)),
]),
),
return Container(
padding: padding,
decoration: BoxDecoration(
color: Surfaces.current.card,
borderRadius: BorderRadius.circular(20)),
child: child,
);
}
}
/// Record on the hero: label and date left, value right. Tappable.
/// One count in the summary card: number, then its label, on one line.
class _CountLine extends StatelessWidget {
final String value;
final String label;
const _CountLine({required this.value, required this.label});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Row(
children: [
Text(value,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
const SizedBox(width: 8),
Expanded(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: surf.textSecondary)),
),
],
);
}
}
/// Best-session card: label and date left, value right. Tappable.
class _HeroRecord extends StatelessWidget {
final String label;
final String value;
@@ -906,13 +1167,13 @@ class _HeroRecord extends StatelessWidget {
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Material(
color: surf.textPrimary.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(12),
color: surf.card,
borderRadius: BorderRadius.circular(20),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 6, 8),
padding: const EdgeInsets.fromLTRB(16, 14, 10, 14),
child: Row(
children: [
Icon(Icons.emoji_events_rounded,
+70 -30
View File
@@ -1,7 +1,9 @@
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'package:flutter/foundation.dart' show kReleaseMode, Uint8List;
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart';
import 'yolo_detector.dart';
import 'preview_screen.dart';
@@ -21,7 +23,8 @@ class CameraScreen extends StatefulWidget {
class _CameraScreenState extends State<CameraScreen> {
CameraController? _controller;
Future<void>? _initializeControllerFuture;
late YOLODetector _yoloDetector;
YOLODetector? _yoloDetector; // null until the model has loaded
bool _processing = false; // a photo is being analysed
Color _bulletColor = Colors.blue; // default fallback
// The variable to hold the number of bullets entered by the user (default set to 5)
@@ -44,7 +47,13 @@ class _CameraScreenState extends State<CameraScreen> {
_loadBulletColor(); // 👈
_loadLanguage();
_loadSelectedTargetColor();
YOLODetector.create().then((detector) => _yoloDetector = detector);
YOLODetector.create().then((detector) {
if (mounted) {
_yoloDetector = detector;
} else {
detector.close(); // screen closed while the model was loading
}
});
}
String _t(String key) {
@@ -149,45 +158,44 @@ class _CameraScreenState extends State<CameraScreen> {
@override
void dispose() {
_controller?.dispose();
_yoloDetector.close();
_yoloDetector?.close();
super.dispose();
}
Future<void> _takePicture() async {
final detector = _yoloDetector;
if (_processing || detector == null) return; // busy, or model still loading
setState(() => _processing = true);
try {
await _initializeControllerFuture;
final clock = Stopwatch()..start();
final file = await _controller!.takePicture();
final imageFile = File(file.path);
final imageBytes = await imageFile.readAsBytes();
final decodedImage = img.decodeImage(imageBytes)!;
final shot = clock.elapsedMilliseconds;
// Crop center square from full image
final width = decodedImage.width;
final height = decodedImage.height;
final size = width < height ? width : height;
final offsetX = (width - size) ~/ 2;
final offsetY = (height - size) ~/ 2;
// Platform JPEG decoder (off the UI thread); the model input is built in
// the background straight from the photo's centre square
final bytes = await File(file.path).readAsBytes();
final photo = await decodePhoto(bytes);
final decoded = clock.elapsedMilliseconds;
final cropped = img.copyCrop(
decodedImage,
x: offsetX,
y: offsetY,
width: size,
height: size,
);
final croppedFile = File('${file.path}_square.jpg')
..writeAsBytesSync(img.encodeJpg(cropped));
final detections = await _yoloDetector.detect(croppedFile);
// Save the square for the preview while the model runs
final squarePath = '${file.path}_square.jpg';
final (_, detections) = await (
saveSquareInBackground(photo, squarePath),
detector.detectPhoto(photo),
).wait;
debugPrint('⏱ detection: photo $shot ms, decode ${decoded - shot} ms '
'(${photo.channels == 4 ? 'platform' : 'Dart'}), '
'model + save ${clock.elapsedMilliseconds - decoded} ms, '
'total ${clock.elapsedMilliseconds} ms');
if (!kReleaseMode) await _compareWithDartDecoder(detector, bytes, detections);
if (!mounted) return;
Navigator.push(
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PreviewScreen(
imagePath: croppedFile.path,
imagePath: squarePath,
detections: detections,
bulletCount: _numberOfBullets, // Pass the bullet count
),
@@ -195,9 +203,34 @@ class _CameraScreenState extends State<CameraScreen> {
);
} catch (e) {
debugPrint('Error taking picture: $e');
} finally {
if (mounted) setState(() => _processing = false);
}
}
// Debug and profile builds only: detect again on the pure-Dart decode of the same photo
// and log how far the results are apart (the platform decoder may round a
// few pixel values differently).
Future<void> _compareWithDartDecoder(YOLODetector detector, Uint8List bytes,
List<DetectionResult> platform) async {
final dart = await detector
.detectPhoto(await Isolate.run(() => decodePhotoDart(bytes)));
String count(List<DetectionResult> r, int c) =>
'${r.where((d) => d.classId == c).length}';
var maxShift = 0.0;
for (final a in platform) {
var nearest = double.infinity;
for (final b in dart.where((b) => b.classId == a.classId)) {
nearest = min(nearest,
sqrt(pow((a.x1 + a.x2 - b.x1 - b.x2) / 2, 2) + pow((a.y1 + a.y2 - b.y1 - b.y2) / 2, 2)));
}
maxShift = max(maxShift, nearest);
}
debugPrint('🔍 decoder check: bullets ${count(platform, 0)} vs ${count(dart, 0)}, '
'rings ${count(platform, 2)} vs ${count(dart, 2)} (platform vs Dart), '
'largest position difference ${maxShift.isFinite ? maxShift.toStringAsFixed(1) : '–'} px');
}
void _showBulletDialog() {
showCameraSheet(
context,
@@ -411,8 +444,15 @@ class _CameraScreenState extends State<CameraScreen> {
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: _takePicture,
child: const Icon(Icons.camera_alt, color: Colors.black),
onPressed: _processing ? null : _takePicture,
child: _processing
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 3, color: Colors.black),
)
: const Icon(Icons.camera_alt, color: Colors.black),
),
body: FutureBuilder(
future: _initializeControllerFuture,
+61 -93
View File
@@ -1,16 +1,17 @@
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../utils/target_colors.dart';
import '../theme/app_theme.dart';
import 'package:flutter/services.dart' show rootBundle, HapticFeedback;
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';
import 'yolo_detector.dart';
import 'dart:convert'; // For JSON encoding
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart';
import '../utils/target_scoring.dart';
class PreviewScreen extends StatefulWidget {
final String imagePath;
@@ -36,22 +37,22 @@ class _PreviewScreenState extends State<PreviewScreen> {
List<Offset> _mappedBullets = [];
late List<DetectionResult> _realImageDetections;
img.Image? _realImageDecoded;
img.Image? _targetImageDecoded;
Future<img.Image?>? _targetImageFuture;
Size? _realImageSize; // the photo; shown from its original bytes
Size? _targetImageSize; // the selected target skin
Future<Size?>? _targetImageFuture;
Uint8List? _cachedTargetImage;
Uint8List? _cachedRealImage;
late String targetAssetPath;
final Offset fixedRingTargetCenter = const Offset(601, 598);
final Offset fixedRingTargetCenter = TargetScoring.center;
final Size fixedRingTargetSize = const Size(355.94, 359.27);
// Scale factors for different target image dimensions
double _scaleFactorX = 1.0;
double _scaleFactorY = 1.0;
img.Image? _defaultTargetDecoded; // Default target for reference dimensions
Size? _defaultTargetSize; // Default target for reference dimensions
int? _highlightedBulletIndex;
@@ -144,8 +145,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
Future<void> _loadDefaultTarget() async {
try {
final byteData = await rootBundle.load('assets/target.png');
final bytes = byteData.buffer.asUint8List();
_defaultTargetDecoded = img.decodeImage(bytes);
_defaultTargetSize = await _imageSize(byteData.buffer.asUint8List());
} catch (e) {
debugPrint("❌ Error loading default target: $e");
}
@@ -164,10 +164,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
_backgroundColor = _getBackgroundColorForTarget(selectedTarget);
// Await the image decoding to ensure it's populated before rebuilding
_targetImageDecoded = await _targetImageFuture;
if (_targetImageDecoded != null) {
_cachedTargetImage =
Uint8List.fromList(img.encodePng(_targetImageDecoded!));
_targetImageSize = await _targetImageFuture;
if (_targetImageSize != null) {
// Calculate scale factors based on target dimensions
_calculateScaleFactors();
}
@@ -178,13 +176,13 @@ class _PreviewScreenState extends State<PreviewScreen> {
}
void _calculateScaleFactors() {
if (_defaultTargetDecoded == null || _targetImageDecoded == null) {
if (_defaultTargetSize == null || _targetImageSize == null) {
_scaleFactorX = 1.0;
_scaleFactorY = 1.0;
return;
}
_scaleFactorX = _targetImageDecoded!.width / _defaultTargetDecoded!.width;
_scaleFactorY = _targetImageDecoded!.height / _defaultTargetDecoded!.height;
_scaleFactorX = _targetImageSize!.width / _defaultTargetSize!.width;
_scaleFactorY = _targetImageSize!.height / _defaultTargetSize!.height;
debugPrint(
"📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY");
@@ -240,29 +238,9 @@ class _PreviewScreenState extends State<PreviewScreen> {
}
}
// Default-target position for a shot scored by hand. TargetScoring puts it
// where it scores exactly [score]; the angle spreads the hand-entered shots.
Offset _generatePositionForScore(int score) {
const double bulletRadius = 25;
final List<double> rings = [14, 68, 123, 177, 232, 286, 342, 397, 455, 510];
// Always generate positions in the default 1200x1200 coordinate system
final center = fixedRingTargetCenter;
final rng = score.clamp(0, 10);
final double distance;
if (rng == 0) {
// Score 0: place outside all rings (bullet center beyond the outermost ring)
distance = rings.last + bulletRadius;
} else if (rng == 10) {
// Score 10: place in the center ring (0-14)
distance = rings[0] / 2;
} else {
// Scores 1-9: place in the middle of the ring
final outerRadius = rings[10 - rng];
final innerRadius = rng < 10 ? rings[10 - rng - 1] : 0;
distance = (outerRadius + innerRadius) / 2;
}
// Calculate angle based on which manual bullet this will be (add randomness for distribution)
final bulletIndex = _manualBulletScores.length;
final angleIncrement = 360.0 / widget.bulletCount;
@@ -270,27 +248,37 @@ class _PreviewScreenState extends State<PreviewScreen> {
// Add random offset within the angle increment to vary positioning
final randomOffset = (Random().nextDouble() - 0.5) * angleIncrement * 0.5;
final angle = baseAngle + randomOffset;
final radians = angle * 3.14159 / 180;
return Offset(
center.dx + distance * cos(radians),
center.dy + distance * sin(radians),
);
return TargetScoring.positionFor(score, angle * pi / 180);
}
Future<img.Image?> _loadAndDecodeTargetImage() async {
// Shown from the asset's own bytes; only its size is read
Future<Size?> _loadAndDecodeTargetImage() async {
final byteData = await rootBundle.load(targetAssetPath);
final bytes = byteData.buffer.asUint8List();
return img.decodeImage(bytes);
_cachedTargetImage = bytes;
return _imageSize(bytes);
}
// Width and height from the image header, without decoding the pixels
static Future<Size?> _imageSize(Uint8List bytes) async {
try {
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
final descriptor = await ui.ImageDescriptor.encoded(buffer);
final size =
Size(descriptor.width.toDouble(), descriptor.height.toDouble());
descriptor.dispose();
buffer.dispose();
return size;
} catch (_) {
return null;
}
}
Future<void> _runDetectionAndMapping() async {
try {
// 1. Load target background image FIRST to calculate scale factors
_targetImageDecoded = await _targetImageFuture;
if (_targetImageDecoded != null) {
_cachedTargetImage =
Uint8List.fromList(img.encodePng(_targetImageDecoded!));
_targetImageSize = await _targetImageFuture;
if (_targetImageSize != null) {
// Calculate scale factors based on target image dimensions
_calculateScaleFactors();
}
@@ -299,16 +287,16 @@ class _PreviewScreenState extends State<PreviewScreen> {
final File realImageFile = File(widget.imagePath);
final realBytes = await realImageFile.readAsBytes();
// 3. Decode the real image (ensure it's valid)
_realImageDecoded = img.decodeImage(realBytes);
if (_realImageDecoded == null) {
// 3. Read its size (the header is enough; the pixels are shown as they are)
_realImageSize = await _imageSize(realBytes);
if (_realImageSize == null) {
debugPrint("❌ Failed to decode image from path: ${widget.imagePath}");
setState(() => _isLoading = false);
return;
}
// 4. Cache decoded image as PNG for rendering
_cachedRealImage = Uint8List.fromList(img.encodePng(_realImageDecoded!));
// 4. Shown from the saved JPEG itself
_cachedRealImage = realBytes;
// 5. Find the detected ring center and size
final ringCamData = _getRingCenterSize(_realImageDetections);
@@ -336,10 +324,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
sizeCam,
fixedRingTargetSize,
);
final score = _scoreForBullet(
mappedToDefaultTarget,
fixedRingTargetCenter, // Always score relative to default target center
);
final score = _scoreForBullet(mappedToDefaultTarget);
return {'bullet': mappedToDefaultTarget, 'score': score};
}).toList();
@@ -631,12 +616,17 @@ class _PreviewScreenState extends State<PreviewScreen> {
};
}).toList();
// Score of every saved bullet, in the same order: hand-entered shots
// keep the score that was entered. The target view shows these as saved.
final scores = [for (int i = 0; i < _mappedBullets.length; i++) _scoreAt(i)];
final targetData = {
'date': dateString,
'totalScore': _totalScore,
'totalScore': scores.fold(0, (a, b) => a + b),
'bulletCount': widget
.bulletCount, // shots fired; missed ones are absent from 'bullets'
'bullets': bulletsInDefaultCoordinates,
'scores': scores,
};
// Write file
@@ -658,10 +648,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
return _manualBulletScores[index - manualStart];
}
final b = _mappedBullets[index];
return _scoreForBullet(
Offset(b.dx / _scaleFactorX, b.dy / _scaleFactorY),
fixedRingTargetCenter,
);
return _scoreForBullet(Offset(b.dx / _scaleFactorX, b.dy / _scaleFactorY));
}
Widget _buildEditController() {
@@ -887,10 +874,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
updated.dx / _scaleFactorX,
updated.dy / _scaleFactorY,
);
final updatedScore = _scoreForBullet(
defaultTargetBullet,
fixedRingTargetCenter,
);
final updatedScore = _scoreForBullet(defaultTargetBullet);
_manualBulletScores[index - manualStartIndex] = updatedScore;
}
});
@@ -1097,21 +1081,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
return Offset(mappedX, mappedY);
}
int _scoreForBullet(Offset bullet, Offset centerOverride) {
const double bulletRadius = 25;
final double distanceToEdge =
(bullet - centerOverride).distance - bulletRadius;
final List<double> rings = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510];
for (int i = 0; i < rings.length; i++) {
if (distanceToEdge <= rings[i]) {
return 10 - i;
}
}
return 0;
}
// Bullet in default target coordinates
int _scoreForBullet(Offset bullet) => TargetScoring.scoreAt(bullet);
int get _totalScore {
// Score is based on the default target coordinate system (1200x1200)
@@ -1127,7 +1098,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
b.dx / _scaleFactorX,
b.dy / _scaleFactorY,
);
return _scoreForBullet(defaultTargetBullet, fixedRingTargetCenter);
return _scoreForBullet(defaultTargetBullet);
}).fold(0, (sum, score) => sum + score);
final manualScore = _manualBulletScores.fold(0, (a, b) => a + b);
@@ -1236,8 +1207,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
: _cachedRealImage;
final imgData = _mode == PreviewMode.mappedTarget
? _targetImageDecoded
: _realImageDecoded;
? _targetImageSize
: _realImageSize;
if (displayImage == null || imgData == null) {
return const Center(
@@ -1418,14 +1389,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
? _manualBulletScores[index -
(_mappedBullets.length -
_manualBulletScores.length)]
: _scoreForBullet(
// Convert bullet back to default coordinate system for scoring
Offset(
bullet.dx / _scaleFactorX,
bullet.dy / _scaleFactorY,
),
fixedRingTargetCenter,
);
// Convert bullet back to default coordinate system for scoring
: _scoreForBullet(Offset(
bullet.dx / _scaleFactorX,
bullet.dy / _scaleFactorY,
));
return Expanded(
child: Padding(
+43 -58
View File
@@ -7,6 +7,7 @@ import 'dart:convert';
import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart';
import '../utils/target_scoring.dart';
import '../utils/target_colors.dart';
import '../widgets/result_share.dart';
import 'session_screen.dart' show targetCount, shotCount;
@@ -30,11 +31,11 @@ class TargetViewScreen extends StatefulWidget {
class _TargetViewScreenState extends State<TargetViewScreen> {
final int _currentIndex = 0;
List<Offset> _bullets = [];
List<int> _scores = []; // score of each bullet, same order as _bullets
List<Offset> _scaledBullets = []; // Bullets scaled to display target size
int _totalScore = 0;
int _shotCount = 0; // shots fired, misses included (bulletCount)
Map<int, int> _folderChartScores = {};
Offset? _targetCenter;
Uint8List? _targetImageBytes;
img.Image? _targetImageDecoded;
String _date = '';
@@ -139,6 +140,25 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
}
}
// Bullets, their scores and the total of one saved target. Newer saves store
// each shot's score (hand-entered shots keep the score that was entered);
// older ones are scored from the positions, by the same rule as saving.
static ({List<Offset> bullets, List<int> scores, int total}) _readTarget(
Map<String, dynamic> data) {
final bullets = [
for (final b in (data['bullets'] as List?) ?? const [])
Offset((b['x'] as num).toDouble(), (b['y'] as num).toDouble())
];
final saved = data['scores'];
final scores = saved is List && saved.length == bullets.length
? [for (final x in saved) (x as num).toInt()]
: [for (final b in bullets) TargetScoring.scoreAt(b)];
final total = data['totalScore'] is int
? data['totalScore'] as int
: scores.fold(0, (a, b) => a + b);
return (bullets: bullets, scores: scores, total: total);
}
Future<void> _loadJsonAndImage() async {
try {
// Load default target for bullet positioning reference
@@ -151,12 +171,6 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
return;
}
// Calculate target center from default target (for bullet positioning)
_targetCenter = Offset(
defaultTargetDecoded.width / 2,
defaultTargetDecoded.height / 2 - 1,
);
// Load selected target for display
final displayByteData = await rootBundle.load(_selectedTargetPath);
final displayBytes = displayByteData.buffer.asUint8List();
@@ -173,20 +187,22 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
if (widget.isCombinedView) {
// In combined view, collect all bullets from all files
final allBullets = <Offset>[];
final allScores = <int>[];
final chartScores = <int, int>{};
var total = 0;
String latestDate = 'Unknown Date';
var shots = 0;
for (var file in widget.jsonFiles) {
final jsonString = await file.readAsString();
final data = jsonDecode(jsonString);
final data = jsonDecode(jsonString) as Map<String, dynamic>;
final target = _readTarget(data);
final bulletsJson = data['bullets'] as List?;
shots += (data['bulletCount'] as int?) ?? bulletsJson?.length ?? 0;
if (bulletsJson != null) {
allBullets.addAll(
bulletsJson.map((b) => Offset(b['x'].toDouble(), b['y'].toDouble())).toList(),
);
}
shots += (data['bulletCount'] as int?) ?? target.bullets.length;
allBullets.addAll(target.bullets);
allScores.addAll(target.scores);
total += target.total;
chartScores[chartScores.length + 1] = target.total;
if (data['date'] != null) {
latestDate = data['date'];
@@ -214,6 +230,9 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
}
_bullets = allBullets;
_scores = allScores;
_totalScore = total;
_folderChartScores = chartScores;
_shotCount = shots;
} else {
// Single file view - load from current file
@@ -240,8 +259,10 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
} else {
_date = rawDate;
}
final bulletsJson = data['bullets'] as List;
_bullets = bulletsJson.map((b) => Offset(b['x'].toDouble(), b['y'].toDouble())).toList();
final target = _readTarget(data as Map<String, dynamic>);
_bullets = target.bullets;
_scores = target.scores;
_totalScore = target.total;
_shotCount = (data['bulletCount'] as int?) ?? _bullets.length;
}
@@ -261,41 +282,12 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
);
}).toList();
_totalScore = _bullets
.map((b) => _scoreForBullet(b, _targetCenter!))
.fold(0, (sum, score) => sum + score);
// Pre-compute folder chart scores to avoid sync file reads in build
if (widget.isCombinedView) {
final chartScores = <int, int>{};
for (int i = 0; i < widget.jsonFiles.length; i++) {
final data = jsonDecode(await widget.jsonFiles[i].readAsString());
final bullets = (data['bullets'] as List?) ?? [];
int s = 0;
for (final b in bullets) {
s += _scoreForBullet(Offset(b['x'].toDouble(), b['y'].toDouble()), _targetCenter!);
}
chartScores[i + 1] = s;
}
_folderChartScores = chartScores;
}
setState(() {});
} catch (e) {
debugPrint("Error loading JSON or image: $e");
}
}
int _scoreForBullet(Offset bullet, Offset center) {
const bulletRadius = 25;
final distance = (bullet - center).distance - bulletRadius;
final rings = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510];
for (int i = 0; i < rings.length; i++) {
if (distance <= rings[i]) return 10 - i;
}
return 0;
}
Future<void> _deleteTarget() async {
try {
final file = File(_targetFilePath);
@@ -317,8 +309,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
// What the screen shows, as one image: target and tiles left, chart right
void _share() {
final center = _targetCenter ?? Offset.zero;
final scores = [for (final b in _bullets) _scoreForBullet(b, center)];
final scores = _scores;
final List<(String, String)> tiles;
final List<MapEntry<int, int>> chart;
@@ -543,10 +534,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
// Scaled bullets are already scaled to display target dimensions
final dx = scaledBullet.dx * scaleX + offsetX;
final dy = scaledBullet.dy * scaleY + offsetY;
// Score is calculated using original bullet position and default target center
final originalBullet = _bullets[i];
final score = _scoreForBullet(
originalBullet, _targetCenter ?? Offset.zero);
final score = _scores[i];
final isHighlighted = widget.isCombinedView
? (_pressedScoreGroup == score)
: (i == _highlightedBulletIndex);
@@ -695,8 +683,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
// Single file view: each shot as a bar
final Map<int, int> shotScores = {};
for (int i = 0; i < _bullets.length; i++) {
final score = _scoreForBullet(_bullets[i], _targetCenter ?? Offset.zero);
shotScores[i + 1] = score; // Shot number starts at 1
shotScores[i + 1] = _scores[i]; // Shot number starts at 1
}
if (shotScores.isEmpty) {
@@ -741,8 +728,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
List<Widget> _buildGroupedScoreButtons() {
final Map<int, int> scoreGroups = {};
for (final bullet in _bullets) {
final score = _scoreForBullet(bullet, _targetCenter!);
for (final score in _scores) {
scoreGroups[score] = (scoreGroups[score] ?? 0) + 1;
}
@@ -835,8 +821,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
final scoredBullets = _bullets.asMap().entries.map((entry) {
final index = entry.key;
final bullet = entry.value;
final score = _scoreForBullet(bullet, _targetCenter ?? Offset.zero);
return {'index': index, 'score': score, 'bullet': bullet};
return {'index': index, 'score': _scores[index], 'bullet': bullet};
}).toList();
// Sort descending by score
+116 -115
View File
@@ -1,6 +1,8 @@
// ======= yolo_detector.dart (updated with imageToInputTensor helper) =======
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:tflite_flutter/tflite_flutter.dart';
import 'package:image/image.dart' as img;
@@ -12,154 +14,153 @@ class DetectionResult {
DetectionResult(this.x1, this.y1, this.x2, this.y2, this.confidence, this.classId);
}
class CroppedImageResult {
final img.Image image;
final int offsetX;
final int offsetY;
final int cropWidth;
final int cropHeight;
/// A decoded camera photo, upright: [channels] bytes per pixel (RGBA from the
/// platform decoder, RGB from the Dart one), row by row.
class Photo {
final Uint8List pixels;
final int width, height, channels;
CroppedImageResult(this.image, this.offsetX, this.offsetY, this.cropWidth, this.cropHeight);
Photo(this.pixels, this.width, this.height, this.channels);
/// The centre square: what detection looks at, the preview shows and gets saved.
int get side => min(width, height);
int get squareX => (width - side) ~/ 2;
int get squareY => (height - side) ~/ 2;
}
/// Decodes a camera JPEG with the platform's decoder, several times faster
/// than the pure-Dart one; falls back to that if it fails. Both apply the
/// photo's EXIF rotation, so the result is upright.
Future<Photo> decodePhoto(Uint8List jpeg) async =>
await decodePhotoNative(jpeg) ?? await Isolate.run(() => decodePhotoDart(jpeg));
Future<Photo?> decodePhotoNative(Uint8List jpeg) async {
try {
final codec = await ui.instantiateImageCodec(jpeg);
final frame = await codec.getNextFrame();
final image = frame.image;
final data = await image.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
final photo = data == null
? null
: Photo(data.buffer.asUint8List(), image.width, image.height, 4);
image.dispose();
codec.dispose();
return photo;
} catch (_) {
return null;
}
}
Photo decodePhotoDart(Uint8List jpeg) {
final decoded = img.decodeImage(jpeg);
if (decoded == null) throw Exception('Could not decode image.');
return Photo(decoded.getBytes(order: img.ChannelOrder.rgb), decoded.width,
decoded.height, 3);
}
/// Model input from the photo's centre square: RGB floats 0..1, row by row,
/// [width] x [height]. Samples the same pixels as copyResize (nearest) of the
/// cropped square, without copying the square first.
Float32List inputFromPhoto(Photo photo, int width, int height) {
final side = photo.side, ox = photo.squareX, oy = photo.squareY;
final ch = photo.channels, rowBytes = photo.width * ch, px = photo.pixels;
final dx = side / width, dy = side / height;
final cols = Int32List(width);
for (int x = 0; x < width; x++) {
cols[x] = (ox + (x * dx).toInt()) * ch;
}
final input = Float32List(width * height * 3);
int i = 0;
for (int y = 0; y < height; y++) {
final row = (oy + (y * dy).toInt()) * rowBytes;
for (int x = 0; x < width; x++) {
final p = row + cols[x];
input[i++] = px[p] / 255.0;
input[i++] = px[p + 1] / 255.0;
input[i++] = px[p + 2] / 255.0;
}
}
return input;
}
/// The centre square as an image, for saving.
img.Image squareOf(Photo photo) {
final full = img.Image.fromBytes(
width: photo.width,
height: photo.height,
bytes: photo.pixels.buffer,
bytesOffset: photo.pixels.offsetInBytes,
numChannels: photo.channels);
return img.copyCrop(full,
x: photo.squareX, y: photo.squareY, width: photo.side, height: photo.side);
}
/// Save the centre square as JPEG in a background isolate.
Future<void> saveSquareInBackground(Photo photo, String path) =>
Isolate.run(() => File(path).writeAsBytesSync(img.encodeJpg(squareOf(photo))));
class YOLODetector {
late Interpreter _interpreter;
late IsolateInterpreter _background; // runs the model off the UI thread
late int inputWidth, inputHeight;
final double confidenceThreshold = 0.4;
YOLODetector._create();
/// Loads the model and runs it once, so the first real photo doesn't pay
/// for the interpreter's one-time setup.
static Future<YOLODetector> create() async {
final detector = YOLODetector._create();
await detector._loadModel();
await detector._run(Float32List(detector.inputWidth * detector.inputHeight * 3));
return detector;
}
Future<void> _loadModel() async {
final options = InterpreterOptions()..threads = 2;
final options = InterpreterOptions()..threads = 4;
_interpreter = await Interpreter.fromAsset('assets/best_float32_nms.tflite', options: options);
_background = await IsolateInterpreter.create(address: _interpreter.address);
final inputTensor = _interpreter.getInputTensor(0);
final inputShape = inputTensor.shape;
final inputShape = _interpreter.getInputTensor(0).shape;
inputHeight = inputShape[1];
inputWidth = inputShape[2];
}
Future<List<DetectionResult>> detect(File imageFile) async {
final bytes = await imageFile.readAsBytes();
final decodedImage = img.decodeImage(bytes);
if (decodedImage == null) throw Exception("Could not decode image.");
return detectFromImage(decodedImage);
// One model run; each row of the result is x1, y1, x2, y2, score, class
Future<List<List<double>>> _run(Float32List input) async {
final numDetections = _interpreter.getOutputTensor(0).shape[1];
final output = [List.generate(numDetections, (_) => List.filled(6, 0.0))];
await _background.run(input.buffer, output);
return output[0];
}
Future<List<DetectionResult>> detectFromImage(img.Image originalImage) async {
final croppedResult = cropToModelAspectRatio(originalImage, inputWidth, inputHeight);
final fixedImage = img.bakeOrientation(croppedResult.image);
final inputTensor = imageToInputTensor(fixedImage, inputWidth, inputHeight);
/// Whole pipeline for a photo file. Coordinates are in pixels of the
/// photo's centre square.
Future<List<DetectionResult>> detect(File imageFile) async =>
detectPhoto(await decodePhoto(await imageFile.readAsBytes()));
final inputBuffer = reshapeFloat(inputTensor.toList(), [1, inputHeight, inputWidth, 3]);
/// Runs the model on [photo]'s centre square; coordinates are in pixels of
/// that square. Not re-entrant: wait for one call to finish before the next.
Future<List<DetectionResult>> detectPhoto(Photo photo) async {
final w = inputWidth, h = inputHeight;
final input = await Isolate.run(() => inputFromPhoto(photo, w, h));
final rows = await _run(input);
final outputShape = _interpreter.getOutputTensor(0).shape;
final numDetections = outputShape[1];
final outputBuffer = List.generate(1, (_) =>
List.generate(numDetections, (_) => List.filled(6, 0.0)));
_interpreter.run(inputBuffer, outputBuffer);
final rawDetections = outputBuffer[0];
final side = photo.side.toDouble();
final results = <DetectionResult>[];
for (var detection in rawDetections) {
final x1 = detection[0];
final y1 = detection[1];
final x2 = detection[2];
final y2 = detection[3];
final score = detection[4];
final classId = detection[5].toInt();
for (final d in rows) {
final score = d[4];
if (score < confidenceThreshold) continue;
// The model outputs coordinates normalized to [0, 1] relative to the input tensor (inputWidth x inputHeight)
// We need to scale back to the original cropped image coordinates
// The cropped image (cropWidth x cropHeight) was resized to (inputWidth x inputHeight)
final scaledX1 = x1 * croppedResult.cropWidth;
final scaledY1 = y1 * croppedResult.cropHeight;
final scaledX2 = x2 * croppedResult.cropWidth;
final scaledY2 = y2 * croppedResult.cropHeight;
// Add offset to get coordinates in the original image space
results.add(DetectionResult(
scaledX1 + croppedResult.offsetX,
scaledY1 + croppedResult.offsetY,
scaledX2 + croppedResult.offsetX,
scaledY2 + croppedResult.offsetY,
score,
classId,
));
// Corners come normalized to [0, 1] of the model input, which is the
// whole square scaled down
results.add(DetectionResult(d[0] * side, d[1] * side, d[2] * side,
d[3] * side, score, d[5].toInt()));
}
return results;
}
void close() {
_background.close();
_interpreter.close();
}
List<List<List<List<double>>>> reshapeFloat(List<double> flat, List<int> dims) {
final d0 = dims[0], d1 = dims[1], d2 = dims[2], d3 = dims[3];
final reshaped = List.generate(d0, (_) =>
List.generate(d1, (_) =>
List.generate(d2, (_) => List.filled(d3, 0.0))));
int index = 0;
for (int i = 0; i < d0; i++) {
for (int j = 0; j < d1; j++) {
for (int k = 0; k < d2; k++) {
for (int l = 0; l < d3; l++) {
reshaped[i][j][k][l] = flat[index++];
}
}
}
}
return reshaped;
}
CroppedImageResult cropToModelAspectRatio(img.Image image, int targetWidth, int targetHeight) {
final targetAspectRatio = targetWidth / targetHeight;
final originalAspectRatio = image.width / image.height;
int cropWidth = image.width;
int cropHeight = image.height;
if (originalAspectRatio > targetAspectRatio) {
cropWidth = (image.height * targetAspectRatio).toInt();
} else {
cropHeight = (image.width / targetAspectRatio).toInt();
}
final offsetX = ((image.width - cropWidth) / 2).toInt();
final offsetY = ((image.height - cropHeight) / 2).toInt();
final croppedImage = img.copyCrop(image, x: offsetX, y: offsetY, width: cropWidth, height: cropHeight);
return CroppedImageResult(croppedImage, offsetX, offsetY, cropWidth, cropHeight);
}
Float32List imageToInputTensor(img.Image inputImage, int width, int height) {
final resized = img.copyResize(inputImage, width: width, height: height);
final Float32List input = Float32List(width * height * 3);
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final pixel = resized.getPixel(x, y);
final r = pixel.r / 255.0;
final g = pixel.g / 255.0;
final b = pixel.b / 255.0;
input[index++] = r;
input[index++] = g;
input[index++] = b;
}
}
return input;
}
}
+48
View File
@@ -0,0 +1,48 @@
import 'dart:math';
import 'dart:ui';
/// The one scoring rule for a shot on the default target (assets/target.png,
/// 1200x1200). Saving, the preview and the target view all use it, so a shot
/// scores the same everywhere.
///
/// A shot counts for the best ring its edge touches: the distance from the
/// centre to the bullet's centre, minus the bullet's radius, is compared with
/// the outer edge of each ring.
class TargetScoring {
TargetScoring._();
static const Offset center = Offset(601, 598);
static const double bulletRadius = 25;
/// Outer edge of ring 10, 9, ... 1, measured from [center].
static const List<double> rings = [
14, 70, 125, 180, 235, 290, 345, 400, 455, 510,
];
/// Score of a shot whose centre is at [bullet] (default target coordinates).
static int scoreAt(Offset bullet) {
final edge = (bullet - center).distance - bulletRadius;
for (int i = 0; i < rings.length; i++) {
if (edge <= rings[i]) return 10 - i;
}
return 0;
}
/// Where to draw a shot that was scored by hand, in direction [angle]
/// (radians): the middle of the band of positions [scoreAt] gives [score]
/// for, so the dot always scores what was entered.
static Offset positionFor(int score, double angle) {
final s = score.clamp(0, 10);
// Distance of the bullet's edge from the centre, middle of the band
final double edge;
if (s == 10) {
edge = (-bulletRadius + rings[0]) / 2; // bullet over the centre
} else if (s == 0) {
edge = rings.last + 30; // just outside the target
} else {
edge = (rings[9 - s] + rings[10 - s]) / 2;
}
final distance = edge + bulletRadius;
return center + Offset(cos(angle), sin(angle)) * distance;
}
}
+20 -10
View File
@@ -1029,6 +1029,26 @@ class AppTranslations {
'Slovenian': 'Tukaj se bodo prikazale shranjene tarče in tvoja statistika',
'German': 'Hier erscheinen gespeicherte Scheiben und deine Statistik',
},
'Statistics / History: your form and progress graph, or the list of all your sessions.': {
'English': 'Statistics / History: your form and progress graph, or the list of all your sessions.',
'Slovenian': 'Statistika / Zgodovina: tvoja forma in graf napredka ali seznam vseh tvojih sej.',
'German': 'Statistik / Verlauf: deine Form und der Fortschrittsgraf oder die Liste aller Einheiten.',
},
'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.': {
'English': 'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.',
'Slovenian': 'Zgodovina: Vse / Treningi / Tekmovanja izbere, katere seje so na seznamu, ne glede na število strelov.',
'German': 'Verlauf: Alle / Trainings / Wettkämpfe wählt, welche Einheiten gelistet werden, mit beliebiger Schusszahl.',
},
'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.': {
'English': 'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.',
'Slovenian': 'Obdobje: ta mesec, zadnji 3 meseci, to leto, vse ali tvoji datumi. Uporabljata ga Statistika in Zgodovina.',
'German': 'Zeitraum: dieser Monat, letzte 3 Monate, dieses Jahr, alle oder eigene Daten. Statistik und Verlauf nutzen ihn beide.',
},
'Tap a session to see all its targets on one target.': {
'English': 'Tap a session to see all its targets on one target.',
'Slovenian': 'Tapni sejo, da vidiš vse njene tarče na eni tarči.',
'German': 'Tippe auf eine Einheit, um alle ihre Scheiben auf einer Scheibe zu sehen.',
},
'Trainings / Tournaments: choose which sessions the statistics count.': {
'English': 'Trainings / Tournaments: choose which sessions the statistics count.',
'Slovenian': 'Treningi / Tekmovanja: izberi, katere seje šteje statistika.',
@@ -1039,11 +1059,6 @@ class AppTranslations {
'Slovenian': 'Streli 1–5: statistika primerja le tarče z enakim številom strelov. Sive številke še nimajo tarč.',
'German': 'Schüsse 1–5: Die Statistik vergleicht nur Scheiben mit gleicher Schusszahl. Graue Zahlen haben noch keine Scheiben.',
},
'Tap a session to see all its targets with the selected number of shots on one target.': {
'English': 'Tap a session to see all its targets with the selected number of shots on one target.',
'Slovenian': 'Tapni sejo za prikaz vseh njenih tarč z izbranim številom strelov na eni tarči.',
'German': 'Tippe auf eine Einheit, um alle ihre Scheiben mit der gewählten Schusszahl auf einer Scheibe zu sehen.',
},
'Three dots on the right or long press: session details, single targets, rename and delete.': {
'English': 'Three dots on the right or long press: session details, single targets, rename and delete.',
'Slovenian': 'Tri pike na desni ali dolg pritisk: podrobnosti seje, posamezne tarče, preimenovanje in brisanje.',
@@ -1065,11 +1080,6 @@ class AppTranslations {
'Slovenian': 'Graf: povprečje strela (leva os) in število točk (desna os). Mesec prikaže vsako sejo meseca, Leto eno točko na mesec; s puščicami greš nazaj po mesecih ali letih. Tapni ali povleci po njem za vrednosti.',
'German': 'Diagramm: Schussdurchschnitt (linke Achse) und Punktzahl (rechte Achse). Monat zeigt jede Einheit eines Monats, Jahr einen Punkt pro Monat; mit den Pfeilen gehst du zu früheren Monaten oder Jahren. Tippe oder ziehe darauf, um die Werte zu sehen.',
},
'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.': {
'English': 'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.',
'Slovenian': 'Obdobje (zraven Zgodovine): ta mesec, zadnji 3 meseci, to leto, vse ali svoji datumi. Uporabljata ga zgornja kartica in seznam.',
'German': 'Zeitraum (neben Verlauf): dieser Monat, letzte 3 Monate, dieses Jahr, alles oder eigene Daten. Die obere Karte und die Liste verwenden ihn beide.',
},
'Period': {
'English': 'Period',
'Slovenian': 'Obdobje',
+27 -20
View File
@@ -27,6 +27,9 @@ class ProgressChart extends StatefulWidget {
final List<ChartSeries> series; // legend and tooltip order
final Color textColor;
final Color gridColor;
// true: the graph takes all the height its parent gives it (inside an
// Expanded); false: a fixed 190 px
final bool expand;
const ProgressChart({
super.key,
@@ -34,6 +37,7 @@ class ProgressChart extends StatefulWidget {
required this.series,
required this.textColor,
required this.gridColor,
this.expand = false,
});
@override
@@ -78,29 +82,32 @@ class _ProgressChartState extends State<ProgressChart> {
@override
Widget build(BuildContext context) {
final graph = LayoutBuilder(
builder: (context, constraints) {
final size = Size(
constraints.maxWidth, widget.expand ? constraints.maxHeight : 190);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (d) => _toggle(d.localPosition, size),
onHorizontalDragUpdate: (d) => _select(d.localPosition, size),
child: CustomPaint(
size: size,
painter: _ChartPainter(
labels: widget.labels,
series: widget.series,
textColor: widget.textColor,
gridColor: widget.gridColor,
selected: _selected,
),
),
);
},
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: widget.expand ? MainAxisSize.max : MainAxisSize.min,
children: [
LayoutBuilder(
builder: (context, constraints) {
final size = Size(constraints.maxWidth, 190);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (d) => _toggle(d.localPosition, size),
onHorizontalDragUpdate: (d) => _select(d.localPosition, size),
child: CustomPaint(
size: size,
painter: _ChartPainter(
labels: widget.labels,
series: widget.series,
textColor: widget.textColor,
gridColor: widget.gridColor,
selected: _selected,
),
),
);
},
),
widget.expand ? Expanded(child: graph) : graph,
const SizedBox(height: 8),
// Legend, centred under the graph
Wrap(