This commit is contained in:
Jan Pleterski
2026-11-13 09:15:17 +01:00
parent d3927aac8a
commit d4bc01f202
21 changed files with 294 additions and 1148 deletions
+17 -232
View File
@@ -12,89 +12,6 @@ import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart';
// DEBUG: Set to true to show scoring rings visualization
const bool _DEBUG_SHOW_SCORING_RINGS = false;
class ScoringRingsPainter extends CustomPainter {
final Offset center;
final double scaleX;
final double scaleY;
final double targetScaleFactorX;
final double targetScaleFactorY;
ScoringRingsPainter({
required this.center,
required this.scaleX,
required this.scaleY,
required this.targetScaleFactorX,
required this.targetScaleFactorY,
});
@override
void paint(Canvas canvas, Size size) {
// Colors for each ring (10 to 1)
final List<Color> ringColors = [
Colors.red, // 10
Colors.orange, // 9
Colors.yellow, // 8
Colors.lime, // 7
Colors.green, // 6
Colors.cyan, // 5
Colors.blue, // 4
Colors.indigo, // 3
Colors.purple, // 2
Colors.pink, // 1
];
// Scoring rings distances from center (in default 1200x1200 space)
// Must match the rings in _generatePositionForScore
final List<double> rings = [14, 68, 123, 177, 232, 286, 342, 397, 455, 510];
// The canvas is already positioned at the image location
// Center should be scaled by target scale factors first (default 1200x1200 to actual target size)
// then by display scale factors (target image to screen)
final scaledCenter = Offset(
center.dx * targetScaleFactorX,
center.dy * targetScaleFactorY,
);
final displayCenter = Offset(
scaledCenter.dx * scaleX,
scaledCenter.dy * scaleY,
);
// Draw each scoring ring with a different color
for (int i = 0; i < rings.length; i++) {
final paint = Paint()
..color = ringColors[i].withValues(alpha: 0.5)
..style = PaintingStyle.stroke
..strokeWidth = 2;
final ringRadius = rings[i];
// Scale by target scale factors (default 1200x1200 to actual target size)
// then by display scale factors (target image to screen)
final scaledRadiusX = ringRadius * targetScaleFactorX * scaleX;
final scaledRadiusY = ringRadius * targetScaleFactorY * scaleY;
final scaledRadius = (scaledRadiusX + scaledRadiusY) / 2;
canvas.drawCircle(displayCenter, scaledRadius, paint);
}
// Draw center point
final centerPaint = Paint()
..color = Colors.red
..style = PaintingStyle.fill;
canvas.drawCircle(displayCenter, 4, centerPaint);
}
@override
bool shouldRepaint(ScoringRingsPainter oldDelegate) {
return center != oldDelegate.center ||
scaleX != oldDelegate.scaleX ||
scaleY != oldDelegate.scaleY ||
targetScaleFactorX != oldDelegate.targetScaleFactorX ||
targetScaleFactorY != oldDelegate.targetScaleFactorY;
}
}
class PreviewScreen extends StatefulWidget {
final String imagePath;
final List<DetectionResult> detections;
@@ -122,7 +39,6 @@ class _PreviewScreenState extends State<PreviewScreen> {
img.Image? _realImageDecoded;
img.Image? _targetImageDecoded;
Future<img.Image?>? _targetImageFuture;
Offset? _targetImageCenterForScoring;
Uint8List? _cachedTargetImage;
Uint8List? _cachedRealImage;
@@ -136,8 +52,6 @@ class _PreviewScreenState extends State<PreviewScreen> {
double _scaleFactorX = 1.0;
double _scaleFactorY = 1.0;
img.Image? _defaultTargetDecoded; // Default target for reference dimensions
Offset?
_scaledTargetCenterForScoring; // Scaled center for scoring with display target
int? _highlightedBulletIndex;
@@ -193,7 +107,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
}
}
} catch (e) {
print("Error loading current folder info: $e");
debugPrint("Error loading current folder info: $e");
}
}
@@ -258,19 +172,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
if (_defaultTargetDecoded == null || _targetImageDecoded == null) {
_scaleFactorX = 1.0;
_scaleFactorY = 1.0;
_scaledTargetCenterForScoring = null;
return;
}
_scaleFactorX = _targetImageDecoded!.width / _defaultTargetDecoded!.width;
_scaleFactorY = _targetImageDecoded!.height / _defaultTargetDecoded!.height;
// Scale the center point for scoring
if (_targetImageCenterForScoring != null) {
_scaledTargetCenterForScoring = Offset(
_targetImageCenterForScoring!.dx * _scaleFactorX,
_targetImageCenterForScoring!.dy * _scaleFactorY,
);
}
debugPrint(
"📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY");
}
@@ -366,15 +272,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
Future<img.Image?> _loadAndDecodeTargetImage() async {
final byteData = await rootBundle.load(targetAssetPath);
final bytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final targetFile = File('${tempDir.path}/target.png');
await targetFile.writeAsBytes(bytes);
final decoded = img.decodeImage(bytes);
if (decoded != null) {
_targetImageCenterForScoring =
Offset(decoded.width / 2, decoded.height / 2 - 1);
}
return decoded;
return img.decodeImage(bytes);
}
Future<void> _runDetectionAndMapping() async {
@@ -468,109 +366,6 @@ class _PreviewScreenState extends State<PreviewScreen> {
}
}
void _manualScoreEntry() {
final missingCount = widget.bulletCount - _mappedBullets.length;
final controllers =
List.generate(missingCount, (_) => TextEditingController());
showDialog(
context: context,
builder: (context) {
return Dialog(
backgroundColor: Colors.grey[900],
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_t('Enter Missing Bullet Scores'),
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 300),
child: SingleChildScrollView(
child: Column(
children: List.generate(missingCount, (index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: TextField(
controller: controllers[index],
keyboardType: TextInputType.number,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText:
'${_t('Bullet Score')} ${_mappedBullets.length + index + 1}',
labelStyle:
const TextStyle(color: Colors.white54),
filled: true,
fillColor: Colors.grey[800],
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: _bulletColor),
),
),
),
);
}),
),
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {
final scores = controllers
.map((c) => int.tryParse(c.text.trim()) ?? 0)
.toList();
setState(() {
for (final score in scores) {
final offset = _generatePositionForScore(score);
// Scale position from default coordinate system to display target size
final scaledOffset = Offset(
offset.dx * _scaleFactorX,
offset.dy * _scaleFactorY,
);
_mappedBullets.add(scaledOffset);
_manualBulletScores.add(score);
}
});
Navigator.pop(context);
},
style: ElevatedButton.styleFrom(
backgroundColor: _bulletColor,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: Text(_t('Add Bullets')),
),
),
],
),
),
);
},
);
}
void _showMissingBulletDialog(int bulletNum) {
showDialog(
context: context,
@@ -761,7 +556,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
await _performSave(lastFolder, false);
} catch (e) {
print("Error saving to last folder: $e");
debugPrint("Error saving to last folder: $e");
}
}
@@ -788,7 +583,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
await _performSave(selectedFolder, isTournament);
} catch (e) {
print("Error saving target data: $e");
debugPrint("Error saving target data: $e");
}
}
@@ -839,15 +634,17 @@ class _PreviewScreenState extends State<PreviewScreen> {
await jsonFile.writeAsString(jsonEncode(targetData));
// Close preview and signal refresh
if (!mounted) return;
Navigator.pop(context, true);
} catch (e) {
print("Error performing save: $e");
debugPrint("Error performing save: $e");
}
}
Widget _buildEditController() {
if (!_isEditMode || _selectedBulletIndexInEdit == null)
if (!_isEditMode || _selectedBulletIndexInEdit == null) {
return const SizedBox.shrink();
}
return Positioned(
bottom: 20,
@@ -986,6 +783,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
final String nextTraining = '$trainingWord $trainingCount';
final String nextTournament = '$tournamentWord $tournamentCount';
if (!mounted) return null;
return showDialog<String>(
context: context,
builder: (context) {
@@ -1164,8 +962,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
int get _totalScore {
// Score is based on the default target coordinate system (1200x1200)
// since bullets were mapped to that system and then scaled for display
// Manual bullets are appended after the detected ones and scored below,
// so take only the detected ones here (at most the remaining shot slots).
final detected = _mappedBullets.length - _manualBulletScores.length;
final autoScore = _mappedBullets
.take(widget.bulletCount - _manualBulletScores.length)
.take(min(detected, widget.bulletCount - _manualBulletScores.length))
.map((b) {
// Scale bullet back to default coordinate system for scoring
final defaultTargetBullet = Offset(
@@ -1358,24 +1159,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
),
),
);
}).toList(),
// DEBUG: Show scoring rings in both modes to verify alignment
if (_DEBUG_SHOW_SCORING_RINGS)
Positioned(
left: offsetX,
top: offsetY,
width: displayWidth,
height: displayHeight,
child: CustomPaint(
painter: ScoringRingsPainter(
center: fixedRingTargetCenter,
scaleX: scaleX,
scaleY: scaleY,
targetScaleFactorX: _scaleFactorX,
targetScaleFactorY: _scaleFactorY,
),
),
),
}),
if (_mode == PreviewMode.mappedTarget)
..._mappedBullets
.asMap()
@@ -1434,14 +1218,15 @@ class _PreviewScreenState extends State<PreviewScreen> {
),
),
);
}).toList(),
}),
],
);
},
),
),
const SizedBox(height: 24),
if (_mappedBullets.isNotEmpty)
// Shown even with no detections, so missed shots can be scored by hand
if (widget.bulletCount > 0)
Column(
children: [
// Score buttons for detected and missing bullets