Don't hardcode ink sparkle spir-v (#102674)

This commit is contained in:
Zachary Anderson
2022-05-04 09:28:45 -07:00
committed by GitHub
parent d1bbd822c0
commit 577919dbfe
11 changed files with 429 additions and 3111 deletions

View File

@@ -43,6 +43,10 @@ const List<Map<String, Object>> kMaterialFonts = <Map<String, Object>>[
},
];
const List<String> kMaterialShaders = <String>[
'shaders/ink_sparkle.frag',
];
/// Injected factory class for spawning [AssetBundle] instances.
abstract class AssetBundleFactory {
/// The singleton instance, pulled from the [AppContext].
@@ -404,11 +408,15 @@ class ManifestAssetBundle implements AssetBundle {
}
final List<_Asset> materialAssets = <_Asset>[
if (flutterManifest.usesMaterialDesign)
..._getMaterialAssets(),
..._getMaterialFonts(),
// Include the shaders unconditionally. They are small, and whether
// they're used is determined only by the app source code and not by
// the Flutter manifest.
..._getMaterialShaders(),
];
for (final _Asset asset in materialAssets) {
final File assetFile = asset.lookupAssetFile(_fileSystem);
assert(assetFile.existsSync());
assert(assetFile.existsSync(), 'Missing ${assetFile.path}');
entries[asset.entryUri.path] ??= DevFSFileContent(assetFile);
}
@@ -490,7 +498,7 @@ class ManifestAssetBundle implements AssetBundle {
}
}
List<_Asset> _getMaterialAssets() {
List<_Asset> _getMaterialFonts() {
final List<_Asset> result = <_Asset>[];
for (final Map<String, Object> family in kMaterialFonts) {
final Object? fonts = family['fonts'];
@@ -504,7 +512,10 @@ class ManifestAssetBundle implements AssetBundle {
}
final Uri entryUri = _fileSystem.path.toUri(asset);
result.add(_Asset(
baseDir: _fileSystem.path.join(Cache.flutterRoot!, 'bin', 'cache', 'artifacts', 'material_fonts'),
baseDir: _fileSystem.path.join(
Cache.flutterRoot!,
'bin', 'cache', 'artifacts', 'material_fonts',
),
relativeUri: Uri(path: entryUri.pathSegments.last),
entryUri: entryUri,
package: null,
@@ -515,6 +526,32 @@ class ManifestAssetBundle implements AssetBundle {
return result;
}
List<_Asset> _getMaterialShaders() {
final String shaderPath = _fileSystem.path.join(
Cache.flutterRoot!,
'packages', 'flutter', 'lib', 'src', 'material', 'shaders',
);
// This file will exist in a real invocation unless the git checkout is
// corrupted somehow, but unit tests generally don't create this file
// in their mock file systems. Leaving it out in those cases is harmless.
if (!_fileSystem.directory(shaderPath).existsSync()) {
return <_Asset>[];
}
final List<_Asset> result = <_Asset>[];
for (final String shader in kMaterialShaders) {
final Uri entryUri = _fileSystem.path.toUri(shader);
result.add(_Asset(
baseDir: shaderPath,
relativeUri: Uri(path: entryUri.pathSegments.last),
entryUri: entryUri,
package: null,
));
}
return result;
}
List<Map<String, Object?>> _parseFonts(
FlutterManifest manifest,
PackageConfig packageConfig, {

View File

@@ -14,6 +14,7 @@ import '../build_system.dart';
import '../depfile.dart';
import 'common.dart';
import 'icon_tree_shaker.dart';
import 'shader_compiler.dart';
/// A helper function to copy an asset bundle into an [environment]'s output
/// directory.
@@ -24,7 +25,9 @@ import 'icon_tree_shaker.dart';
/// included in the final bundle, but not the AssetManifest.json file.
///
/// Returns a [Depfile] containing all assets used in the build.
Future<Depfile> copyAssets(Environment environment, Directory outputDirectory, {
Future<Depfile> copyAssets(
Environment environment,
Directory outputDirectory, {
Map<String, DevFSContent>? additionalContent,
required TargetPlatform targetPlatform,
BuildMode? buildMode,
@@ -72,6 +75,12 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory, {
fileSystem: environment.fileSystem,
artifacts: environment.artifacts,
);
final ShaderCompiler shaderCompiler = ShaderCompiler(
processManager: environment.processManager,
logger: environment.logger,
fileSystem: environment.fileSystem,
artifacts: environment.artifacts,
);
final Map<String, DevFSContent> assetEntries = <String, DevFSContent>{
...assetBundle.entries,
@@ -100,6 +109,9 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory, {
input: content.file as File,
outputPath: file.path,
relativePath: entry.key,
) && !await shaderCompiler.compileShader(
input: content.file as File,
outputPath: file.path,
)) {
await (content.file as File).copy(file.path);
}
@@ -258,6 +270,7 @@ class CopyAssets extends Target {
List<Source> get inputs => const <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/assets.dart'),
...IconTreeShaker.inputs,
...ShaderCompiler.inputs,
];
@override

View File

@@ -18,6 +18,7 @@ import 'assets.dart';
import 'dart_plugin_registrant.dart';
import 'icon_tree_shaker.dart';
import 'localizations.dart';
import 'shader_compiler.dart';
/// Copies the pre-built flutter bundle.
// This is a one-off rule for implementing build bundle in terms of assemble.
@@ -33,6 +34,7 @@ class CopyFlutterBundle extends Target {
Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug),
Source.pattern('{BUILD_DIR}/app.dill'),
...IconTreeShaker.inputs,
...ShaderCompiler.inputs,
];
@override

View File

@@ -19,6 +19,7 @@ import '../exceptions.dart';
import 'assets.dart';
import 'common.dart';
import 'icon_tree_shaker.dart';
import 'shader_compiler.dart';
/// Supports compiling a dart kernel file to an assembly file.
///
@@ -439,6 +440,7 @@ abstract class IosAssetBundle extends Target {
Source.pattern('{BUILD_DIR}/App.framework/App'),
Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
...IconTreeShaker.inputs,
...ShaderCompiler.inputs,
];
@override

View File

@@ -0,0 +1,98 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:process/process.dart';
import '../../artifacts.dart';
import '../../base/common.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../base/logger.dart';
import '../../convert.dart';
import '../build_system.dart';
/// A class the wraps the functionality of the Impeller shader compiler
/// impellerc.
class ShaderCompiler {
ShaderCompiler({
required ProcessManager processManager,
required Logger logger,
required FileSystem fileSystem,
required Artifacts artifacts,
}) : _processManager = processManager,
_logger = logger,
_fs = fileSystem,
_artifacts = artifacts;
final ProcessManager _processManager;
final Logger _logger;
final FileSystem _fs;
final Artifacts _artifacts;
/// The [Source] inputs that targets using this should depend on.
///
/// See [Target.inputs].
static const List<Source> inputs = <Source>[
Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/shader_compiler.dart'),
Source.hostArtifact(HostArtifact.impellerc),
];
/// Calls impellerc, which transforms the [input] glsl shader into a
/// platform specific shader at [outputPath].
///
/// All parameters are required.
///
/// If the input file is not a fragment shader, this returns false.
/// If the shader compiler subprocess fails, it will [throwToolExit].
/// Otherwise, it will return true.
Future<bool> compileShader({
required File input,
required String outputPath,
}) async {
if (!input.path.endsWith('.frag')) {
return false;
}
final File impellerc = _fs.file(
_artifacts.getHostArtifact(HostArtifact.impellerc),
);
if (!impellerc.existsSync()) {
throw ShaderCompilerException._(
'The impellerc utility is missing at "${impellerc.path}". '
'Run "flutter doctor".',
);
}
final List<String> cmd = <String>[
impellerc.path,
// TODO(zanderso): When impeller is enabled, the correct flags for the
// target backend will need to be passed.
// https://github.com/flutter/flutter/issues/102853
'--flutter-spirv',
'--spirv=$outputPath',
'--input=${input.path}',
];
final Process impellercProcess = await _processManager.start(cmd);
final int code = await impellercProcess.exitCode;
if (code != 0) {
_logger.printTrace(await utf8.decodeStream(impellercProcess.stdout));
_logger.printError(await utf8.decodeStream(impellercProcess.stderr));
throw ShaderCompilerException._(
'Shader compilation of "${input.path}" to "$outputPath" '
'failed with exit code $code.',
);
}
return true;
}
}
class ShaderCompilerException implements Exception {
ShaderCompilerException._(this.message);
final String message;
@override
String toString() => 'ShaderCompilerException: $message\n\n';
}

View File

@@ -13,6 +13,7 @@ import 'build_info.dart';
import 'build_system/build_system.dart';
import 'build_system/depfile.dart';
import 'build_system/targets/common.dart';
import 'build_system/targets/shader_compiler.dart';
import 'bundle.dart';
import 'cache.dart';
import 'devfs.dart';
@@ -148,6 +149,13 @@ Future<void> writeBundle(
}
bundleDir.createSync(recursive: true);
final ShaderCompiler shaderCompiler = ShaderCompiler(
processManager: globals.processManager,
logger: globals.logger,
fileSystem: globals.fs,
artifacts: globals.artifacts!,
);
// Limit number of open files to avoid running out of file descriptors.
final Pool pool = Pool(64);
await Future.wait<void>(
@@ -161,7 +169,15 @@ Future<void> writeBundle(
// and the native APIs will look for files this way.
final File file = globals.fs.file(globals.fs.path.join(bundleDir.path, entry.key));
file.parent.createSync(recursive: true);
await file.writeAsBytes(await entry.value.contentsAsBytes());
final DevFSContent devFSContent = entry.value;
if (devFSContent is DevFSFileContent) {
final File input = devFSContent.file as File;
if (!await shaderCompiler.compileShader(input: input, outputPath: file.path)) {
input.copySync(file.path);
}
} else {
await file.writeAsBytes(await entry.value.contentsAsBytes());
}
} finally {
resource.release();
}