How to build Skia 和 canvaskit

 

docker镜像作为编译环境:

编译canvaskit的docker相关文件放在:skia/infra/canvaskit/docker

[root@base11:/home/chromium/skia/infra/canvaskit/docker]# ls
canvaskit-emsdk  Makefile
[root@base11:/home/chromium/skia/infra/canvaskit/docker]# more Makefile 
EMSDK_VERSION=3.1.3_v1

publish_canvaskit_emsdk:
	docker build -t canvaskit-emsdk ./canvaskit-emsdk/
	docker tag canvaskit-emsdk gcr.io/skia-public/canvaskit-emsdk:${EMSDK_VERSION}
	docker push gcr.io/skia-public/canvaskit-emsdk:${EMSDK_VERSION}

换目录,执行这里的,不是上面的了:skia/infra/wasm-common/docker

执行:make publish_canvaskit_emsdk

会自动按照 canvaskit-emsdk 目录下的 Dockerfile 下载编译环境。

注释掉 skia/modules/canvaskit/compile.sh 中需要fq部分。

编译:docker run -v /home/skia:/SRC -v /home/skia/out:/OUT canvaskit-emsdk /SRC/infra/canvaskit/build_canvaskit.sh  debug

 

这个链接包含如何编译运行文档:https://github.com/google/skia/blob/main/modules/canvaskit/README.md

infra/wasm-common/docker/README.md 有测试docker环境好用否的命令。

emsdk-base

This image has an Emscripten SDK environment that can be used for compiling projects (e.g. Skia's PathKit) to WASM/asm.js.

This image tracks the official emscripten Docker image and installs python 2 (which some of our scripts still use).

make publish_emsdk_base

For testing the image locally, the following flow can be helpful:

docker build -t emsdk-base ./emsdk-base/
# Run bash in it to poke around and make sure things are properly installed
docker run -it emsdk-base /bin/bash
# Compile PathKit with the local image
docker run -v $SKIA_ROOT:/SRC -v $SKIA_ROOT/out/dockerpathkit:/OUT emsdk-base /SRC/infra/pathkit/build_pathkit.sh

本地环境编译

1,emsdk Download and install

https://emscripten.org/docs/getting_started/downloads.html

自己更新 emsdk,指定版本:

 emsdk install 3.1.3

# Fetch the latest registry of available tools.
./emsdk update

# Download and install the latest SDK tools.
./emsdk install latest

# Set up the compiler configuration to point to the "latest" SDK.
./emsdk activate latest

# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh

2,在目录 skia/modules/canvaskit

执行执行 ./compile.sh

 

搭建运行本地示例

Compile and Run Local Example

https://github.com/google/skia/blob/main/modules/canvaskit/README.md

# The following installs all npm dependencies and only needs to be when setting up
# or if our npm dependencies have changed (rarely).
npm ci

make release  # make debug is much faster and has better error messages
make local-example

This will print a local endpoint for viewing the example. You can experiment with the CanvasKit API by modifying ./npm_build/example.html and refreshing the page. For some more experimental APIs, there's also ./npm_build/extra.html.

For other available build targets, see Makefile and compile.sh. For example, building a stripped-down version of CanvasKit with no text support or any of the "extras", one might run:

./compile.sh no_skottie no_particles no_font

Such a stripped-down version is about half the size of the default release build.


参考:


什么是 CanvasKit ?

版权声明:本文为CSDN博主「张驰Terry」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/terrychinaz/article/details/113940795

CanvasKit是以WASM为编译目标的Web平台图形绘制接口,其目标是将Skia的图形API导出到Web平台。从代码提交记录来看,CanvasKit作为了一个Module放置在整个代码仓库中,最早的一次提交记录在2018年9月左右,是一个比较新的codebase

本文简单介绍一下Skia是如何编译为Web平台的,其性能以及未来的可应用场景

编译原理
整个canvaskit模块的代码量非常少:

.gitignore
CHANGELOG.md
Makefile
WasmAliases.h
canvaskit/ 发布代码,canvaskit介绍文档
canvaskit_bindings.cpp
compile.sh 编译脚本
cpu.js
debug.js
externs.js
fonts/ 字体资源文件
gpu.js
helper.js
htmlcanvas/
interface.js
karma.bench.conf.js
karma.conf.js
package.json
particles_bindings.cpp
perf/ 性能数据
postamble.js
preamble.js
ready.js
release.js
serve.py
skottie.js
skottie_bindings.cpp
tests/ 测试代码

整个模块我们可以看到其实没有修改包括任何skia的代码文件,只是在编译时指明了skia的源码依赖,同时写了一些胶水代码,从这里可以看出skia迁移至WASM并没有付出很多额外的改造工作。

编译
设置好WASM工具链EmscriptenSDK的环境变量后运行compile.sh就会在out文件夹中得到canvaskit.js和canvaskit.wasm这两个编译产物,这里为了分析选择编译一个debug版本:

./compile.sh debug

debug版本会得到一个未混淆的canvaskit.js,方便我们分析其实现

编译产物浅析
为了快速了解整个模块的情况,直接观察canvaskit.js和canvaskit.wasm文件,先来看下canvaskit.jsjs代码量比较大,这里摘取一段最能展示其运行原理的代码:

function makeWebGLContext(canvas, attrs) {
// These defaults come from the emscripten _emscripten_webgl_create_context
var contextAttributes = {
alpha: get(attrs, 'alpha', 1),
depth: get(attrs, 'depth', 1),
stencil: get(attrs, 'stencil', 0),
antialias: get(attrs, 'antialias', 1),
premultipliedAlpha: get(attrs, 'premultipliedAlpha', 1),
preserveDrawingBuffer: get(attrs, 'preserveDrawingBuffer', 0),
preferLowPowerToHighPerformance: get(attrs, 'preferLowPowerToHighPerformance', 0),
failIfMajorPerformanceCaveat: get(attrs, 'failIfMajorPerformanceCaveat', 0),
majorVersion: get(attrs, 'majorVersion', 1),
minorVersion: get(attrs, 'minorVersion', 0),
enableExtensionsByDefault: get(attrs, 'enableExtensionsByDefault', 1),
explicitSwapControl: get(attrs, 'explicitSwapControl', 0),
renderViaOffscreenBackBuffer: get(attrs, 'renderViaOffscreenBackBuffer', 0),
};
if (!canvas) {
SkDebug('null canvas passed into makeWebGLContext');
return 0;
}
// This check is from the emscripten version
if (contextAttributes['explicitSwapControl']) {
SkDebug('explicitSwapControl is not supported');
return 0;
}
// GL is an enscripten provided helper
// See <https://github.com/emscripten-core/emscripten/blob/incoming/src/library_webgl.js>
return GL.createContext(canvas, contextAttributes);
}

CanvasKit.GetWebGLContext = function(canvas, attrs) {
return makeWebGLContext(canvas, attrs);
};

var GL= {
// ...
init:function () {
GL.miniTempBuffer = new Float32Array(GL.MINI_TEMP_BUFFER_SIZE);
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
GL.miniTempBufferViews[i] = GL.miniTempBuffer.subarray(0, i+1);
}
},
//...
createContext:function (canvas, webGLContextAttributes) {
var ctx = (canvas.getContext("webgl", webGLContextAttributes)
|| canvas.getContext("experimental-webgl", webGLContextAttributes));
return ctx && GL.registerContext(ctx, webGLContextAttributes);
},registerContext:function (ctx, webGLContextAttributes) {
var handle = _malloc(8); // Make space on the heap to store GL context attributes that need to be accessible as shared between threads.
assert(handle, 'malloc() failed in GL.registerContext!');
var context = {
handle: handle,
attributes: webGLContextAttributes,
version: webGLContextAttributes.majorVersion,
GLctx: ctx
};
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
if (ctx.canvas) ctx.canvas.GLctxObject = context;
GL.contexts[handle] = context;
if (typeof webGLContextAttributes.enableExtensionsByDefault === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
GL.initExtensions(context);
}
return handle;
},makeContextCurrent:function (contextHandle) {
GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object.
Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object.
return !(contextHandle && !GLctx);
},
// ...
}

代码中出现了大量的WebGL指令和2d的绘制js代码,其实这一块就是EmscriptenSDK对OpenGL的胶水代码(https://emscripten.org/docs/porting/multimedia_and_graphics/OpenGL-support.html)), 换言之,canvaskit的绘制代码没有脱离浏览器提供的webgl和context2d的相关接口,毕竟这也是目前在浏览器进行绘制操作的唯一途径

那编译的wasm文件做了啥呢?简单看一下对应wasm的一部分代码, 这也是一个比较庞大的文件,我们只关注一下wasm和js连接的桥梁代码:

(import "env" "_eglGetCurrentDisplay" (func $_eglGetCurrentDisplay (result i32)))
(import "env" "_eglGetProcAddress" (func $_eglGetProcAddress (param i32) (result i32)))
(import "env" "_eglQueryString" (func $_eglQueryString (param i32 i32) (result i32)))
(import "env" "_emscripten_glActiveTexture" (func $_emscripten_glActiveTexture (param i32)))
(import "env" "_emscripten_glAttachShader" (func $_emscripten_glAttachShader (param i32 i32)))
(import "env" "_emscripten_glBeginQueryEXT" (func $_emscripten_glBeginQueryEXT (param i32 i32)))
(import "env" "_emscripten_glBindAttribLocation" (func $_emscripten_glBindAttribLocation (param i32 i32 i32)))
(import "env" "_emscripten_glBindBuffer" (func $_emscripten_glBindBuffer (param i32 i32)))
(import "env" "_emscripten_glBindFramebuffer" (func $_emscripten_glBindFramebuffer (param i32 i32)))
(import "env" "_emscripten_glBindRenderbuffer" (func $_emscripten_glBindRenderbuffer (param i32 i32)))
(import "env" "_emscripten_glBindTexture" (func $_emscripten_glBindTexture (param i32 i32)))
(import "env" "_emscripten_glClear" (func $_emscripten_glClear (param i32)))
(import "env" "_emscripten_glClearColor" (func $_emscripten_glClearColor (param f64 f64 f64 f64)))
(import "env" "_emscripten_glClearDepthf" (func $_emscripten_glClearDepthf (param f64)))
(import "env" "_emscripten_glCompileShader" (func $_emscripten_glCompileShader (param i32)))
...

这里省略了一部分,但是仍然可以看出,wasm对绘制的支持全部依赖其运行环境中js注入的函数实现

以这里的_emscripten_glBindTexture函数为例,对应到js为:

var asmGlobalArg = {}

var asmLibraryArg = {
"_emscripten_glBindTexture": _emscripten_glBindTexture // .... 上文wasm中的函数注册,这里略去,只保留_emscripten_glBindTexture
}
Module['asm'] = function(global, env, providedBuffer) {
// memory was already allocated (so js could use the buffer)
env['memory'] = wasmMemory
;
// import table
env['table'] = wasmTable = new WebAssembly.Table({
'initial': 1155075,
'maximum': 1155075,
'element': 'anyfunc'
});
env['__memory_base'] = 1024; // tell the memory segments where to place themselves
env['__table_base'] = 0; // table starts at 0 by default (even in dynamic linking, for the main module)

var exports = createWasm(env); // 加载WASM对象, env即WASM对象加载时所需要的上下文,包括内存大小,函数表,和堆栈起始地址
assert(exports, 'binaryen setup failed (no wasm support?)');
return exports;
};
// EMSCRIPTEN_START_ASM
var asm =Module["asm"]// EMSCRIPTEN_END_ASM
(asmGlobalArg, asmLibraryArg, buffer);
function _emscripten_glBindTexture(target, texture) {
GL.validateGLObjectID(GL.textures, texture, 'glBindTexture', 'texture');
GLctx.bindTexture(target, GL.textures[texture]);
}

GLctx通过代码我们也能找到对应:

createContext:function (canvas, webGLContextAttributes) {
var ctx = (canvas.getContext("webgl", webGLContextAttributes)
|| canvas.getContext("experimental-webgl", webGLContextAttributes));
return ctx && GL.registerContext(ctx, webGLContextAttributes);
},registerContext:function (ctx, webGLContextAttributes) {
var handle = _malloc(8); // Make space on the heap to store GL context attributes that need to be accessible as shared between threads.
assert(handle, 'malloc() failed in GL.registerContext!');
var context = {
handle: handle,
attributes: webGLContextAttributes,
version: webGLContextAttributes.majorVersion,
GLctx: ctx
};
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
if (ctx.canvas) ctx.canvas.GLctxObject = context;
GL.contexts[handle] = context;
if (typeof webGLContextAttributes.enableExtensionsByDefault === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
GL.initExtensions(context);
}
return handle;
},makeContextCurrent:function (contextHandle) {

GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object.
Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object. // GLCtx变量
return !(contextHandle && !GLctx);
}

所以这里的bindTexture实际上就是WebGL的bindTexture指令(https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindTexture#Syntax)

分析到这里,我们可以得到一个基本结论: canvaskit中绘制的实现全部在canvaskit.js中调用浏览器绘制API来实现,而计算相关的内容全部放在了wasm中实现

编译脚本解析
通过对编译产物的分析,我们可以发现canvaskit绝大部分的绘制都是借助了Web API中的2d或webgl绘制API来完成的。这里需要分析的是canvaskit如何搭建了skia原生绘制代码和浏览器绘制API的桥梁。

看到compile.sh发现最后一句话涉及到很多canvaskit目录下的文件,因此直接结合编译日志的相关内容分析。

其他的日志都是常规的skia编译命令,只不过执行程序换成了em++而已,em++就是EmscriptenSDK中的编译器命令,可以类比为g++,这些命令会把skia编译为几个静态库

我们略过之前的skia编译命令来到最后一段,这是真正生成WASM产物的地方,其中有大量的逻辑是涉及到canvaskit中的胶水代码的。略去链接, 编译器优化设置, Skia静态库路径的指定, Skia宏定义和头文件路径指定,我们将会得到:

script

/Users/JianGuo/VSCodeProject/emsdk/emscripten/1.38.28/em++ \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/debug.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/cpu.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/gpu.js \\
--bind \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/preamble.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/helper.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/interface.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/skottie.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/preamble.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/util.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/color.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/font.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/canvas2dcontext.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/htmlcanvas.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/imagedata.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/lineargradient.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/path2d.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/pattern.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/radialgradient.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/htmlcanvas/postamble.js \\
--pre-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/postamble.js \\
--post-js /Users/JianGuo/Desktop/skia/skia/modules/canvaskit/ready.js \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/fonts/NotoMono-Regular.ttf.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/canvaskit_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/particles_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/skottie_bindings.cpp \\
modules/skottie/utils/SkottieUtils.cpp \\
-s ALLOW_MEMORY_GROWTH=1 \\ # 允许申请比TOTAL_MEMORY更大的内存
-s EXPORT_NAME=CanvasKitInit \\ # js中Module的名字
-s FORCE_FILESYSTEM=0 \\ # 开启文件系统支持,用于js中对native的文件系统进行模拟
-s MODULARIZE=1 \\ #启用Module的方式生成js,开启后编译的js产物将拥有一个Module作用域,而非全局作用域
-s NO_EXIT_RUNTIME=1 \\ # 禁止使用exit函数
-s STRICT=1 \\ # 确保编译器不使用弃用语法
-s TOTAL_MEMORY=128MB \\ # WASM分配的总内存,如果比此内存更大的场景就需要扩展堆大小
-s USE_FREETYPE=1 \\ # 使用emscripten-ports导出的freetype库
-s USE_LIBPNG=1 \\ # 使用emscripten-ports导出的libpng库
-s WARN_UNALIGNED=1 \\ # 编译时警告未对齐(align)
-s USE_WEBGL2=0 \\ # 不使用WebGL2
-s WASM=1 \\ # 编译为WASM
-o out/canvaskit_wasm_debug/canvaskit.js # 指定编译路径

其中,pre-js <file>表示将指定文件的内容插入到生成的js文件前, post-js表示将指定文件的内容插入到生成的js文件后,我们以skia/modules/canvaskit/htmlcanvas/htmlcanvas.js为例,看看这些插入的文件都干了啥:

CanvasKit.MakeCanvas = function(width, height) {
var surf = CanvasKit.MakeSurface(width, height);
if (surf) {
return new HTMLCanvas(surf);
}
return null;
}

function HTMLCanvas(skSurface) {
this._surface = skSurface;
this._context = new CanvasRenderingContext2D(skSurface.getCanvas());
this._toCleanup = [];
this._fontmgr = CanvasKit.SkFontMgr.RefDefault();

// Data is either an ArrayBuffer, a TypedArray, or a Node Buffer
this.decodeImage = function(data) {
// ...
}

this.loadFont = function(buffer, descriptors) {
//...
}

this.makePath2D = function(path) {
//...
}

// A normal <canvas> requires that clients call getContext
this.getContext = function(type) {
//...
}

this.toDataURL = function(codec, quality) {
//...
}

this.dispose = function() {
//...
}
}

其实就是对齐了一下浏览器实现,同时对齐了一下Skia内部的接口而已。最后我们还剩下一段没有分析:

script

/Users/JianGuo/VSCodeProject/emsdk/emscripten/1.38.28/em++ \\
...
--bind \\
...
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/fonts/NotoMono-Regular.ttf.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/canvaskit_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/particles_bindings.cpp \\
/Users/JianGuo/Desktop/skia/skia/modules/canvaskit/skottie_bindings.cpp \\
modules/skottie/utils/SkottieUtils.cpp \\
...

根据文档,这段命令要求em++以Embind(https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#embind)连接C++代码和JS代码%E8%BF%9E%E6%8E%A5C++%E4%BB%A3%E7%A0%81%E5%92%8CJS%E4%BB%A3%E7%A0%81), embind简单来说就是emscriptenSDK提供的将C/C++代码暴露给JavaScript的便捷能力。这里不做重点介绍,我们直接看canvaskit用到的一个代码:

particles_bindings.cpp:

// ...
#include <emscripten.h>
#include <emscripten/bind.h>

using namespace emscripten;

EMSCRIPTEN_BINDINGS(Particles) {
class_<SkParticleEffect>("SkParticleEffect")
.smart_ptr<sk_sp<SkParticleEffect>>("sk_sp<SkParticleEffect>")
.function("draw", &SkParticleEffect::draw, allow_raw_pointers())
.function("start", select_overload<void (double, bool)>(&SkParticleEffect::start))
.function("update", select_overload<void (double)>(&SkParticleEffect::update));

function("MakeParticles", optional_override([](std::string json)->sk_sp<SkParticleEffect> {
static bool didInit = false;
if (!didInit) {
REGISTER_REFLECTED(SkReflected);
SkParticleAffector::RegisterAffectorTypes();
SkParticleDrawable::RegisterDrawableTypes();
didInit = true;
}
SkRandom r;
sk_sp<SkParticleEffectParams> params(new SkParticleEffectParams());
skjson::DOM dom(json.c_str(), json.length());
SkFromJsonVisitor fromJson(dom.root());
params->visitFields(&fromJson);
return sk_sp<SkParticleEffect>(new SkParticleEffect(std::move(params), r));
}));
constant("particles", true);

}

上面代码经过em++编译后会直接将其功能内嵌进wasm文件中。至此,整个编译流程就分析完了

小结
这里用一张图来总结一下整个canvaskit的编译流程, 图中省去了编译器优化和js优化的流程:

 

 

可应用场景
根据官方文档(https://skia.org/user/modules/canvaskit)), canvaskit基于skia的API设计向web平台提供了更加方便的图形接口,可以说起到了类似GLWrapper的作用。

得益于Skia本身的其他扩展功能,canvaskit相比于浏览器原生绘制能力,支持了许多更加上层的业务级别功能,例如skia的动画模块skottie(https://skia.org/user/modules/skottie)

Skia中的skottie本身就支持Lottie动画解析和播放,由于Skia良好的跨平台能力,Android和iOS平台现在均可以使用Skia框架来播放Lottie动画,canvaskit则运用WebAssembly的技术来将跨平台的范围扩展到web上,使得web平台可以通过canvaskit的skottie相关接口直接播放lottie动画

对于Web应用而言,canvaskit提供了开发者更加友好的图形接口,并提供了常见的图形概念(例如Bitmap,Path等),减少了上层应用开发者对于绘制接口的理解负担,开发者只需要理解Skia的图形概念即可开发图形界面,有了skia他们也不需要理解复杂的webgl指令。

小结
得益于WASM的理念和EmscriptenSDK的能力,越来越多的native库可以直接导出web上供开发者使用。CanvasKit可以说是C++ Library向Web平台迁移的又一最佳实践。EmscriptenSDK已经做到将Skia这种规模的C++项目以WASM的方式迁移至Web平台,并保证其代码功能的一致性。整个迁移的过程的代价也就是编译工具链的替换和一部分胶水代码。
————————————————
版权声明:本文为CSDN博主「张驰Terry」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/terrychinaz/article/details/113940795

 

1

Install depot_tools and Git

Follow the instructions on Installing Chromium’s depot_tools to download depot_tools (which includes gclient, git-cl, and Ninja). Below is a summary of the necessary steps.

git clone 'https://chromium.googlesource.com/chromium/tools/depot_tools.git'
export PATH="${PWD}/depot_tools:${PATH}"

depot_tools will also install Git on your system, if it wasn’t installed already.

Clone the Skia repository

Skia can either be cloned using git or the fetch tool that is installed with depot_tools.

git clone https://skia.googlesource.com/skia.git
# or
# fetch skia
cd skia
python2 tools/git-sync-deps

How to build Skia

Make sure you have first followed the instructions to download Skia.

Skia uses GN to configure its builds.

is_official_build and Third-party Dependencies

Most users of Skia should set is_official_build=true, and most developers should leave it to its false default.

This mode configures Skia in a way that’s suitable to ship: an optimized build with no debug symbols, dynamically linked against its third-party dependencies using the ordinary library search path.

In contrast, the developer-oriented default is an unoptimized build with full debug symbols and all third-party dependencies built from source and embedded into libskia. This is how we do all our manual and automated testing.

Skia offers several features that make use of third-party libraries, like libpng, libwebp, or libjpeg-turbo to decode images, or ICU and sftnly to subset fonts. All these third-party dependencies are optional and can be controlled by a GN argument that looks something like skia_use_foo for appropriate foo.

If skia_use_foo is enabled, enabling skia_use_system_foo will build and link Skia against the headers and libraries found on the system paths. is_official_build=true enables all skia_use_system_foo by default. You can use extra_cflags and extra_ldflags to add include or library paths if needed.

Supported and Preferred Compilers

While Skia should compile with GCC, MSVC, and other compilers, a number of routines in Skia’s software backend have been written to run fastest when compiled with Clang. If you depend on software rasterization, image decoding, or color space conversion and compile Skia with a compiler other than Clang, you will see dramatically worse performance. This choice was only a matter of prioritization; there is nothing fundamentally wrong with non-Clang compilers. So if this is a serious issue for you, please let us know on the mailing list.

Skia makes use of C++17 language features (compiles with -std=c++17 flag) and thus requires a C++17 compatible compiler. Clang 5 and later implement all of the features of the c++17 standard. Older compilers that lack C++17 support may produce non-obvious compilation errors. You can configure your build to use specific executables for cc and cxx invocations using e.g. --args='cc="clang-6.0" cxx="clang++6.0"' GN build arguments, as illustrated in Quickstart. This can be useful for building Skia without needing to modify your machine’s default compiler toolchain.

Quickstart

Run gn gen to generate your build files. As arguments to gn gen, pass a name for your build directory, and optionally --args= to configure the build type.

To build Skia as a static library in a build directory named out/Static:

bin/gn gen out/Static --args='is_official_build=true'

To build Skia as a shared library (DLL) in a build directory named out/Shared:

bin/gn gen out/Shared --args='is_official_build=true is_component_build=true'

If you find that you don’t have bin/gn, make sure you’ve run:

python2 tools/git-sync-deps

For a list of available build arguments, take a look at gn/skia.gni, or run:

bin/gn args out/Debug --list

GN allows multiple build folders to coexist; each build can be configured separately as desired. For example:

bin/gn gen out/Debug
bin/gn gen out/Release  --args='is_debug=false'
bin/gn gen out/Clang    --args='cc="clang" cxx="clang++"'
bin/gn gen out/Cached   --args='cc_wrapper="ccache"'
bin/gn gen out/RTTI     --args='extra_cflags_cc=["-frtti"]'

Once you have generated your build files, run Ninja to compile and link Skia:

ninja -C out/Static

If some header files are missing, install the corresponding dependencies:

tools/install_dependencies.sh

To pull new changes and rebuild:

git pull
python tools/git-sync-deps
ninja -C out/Static

Android

To build Skia for Android you need an Android NDK.

If you do not have an NDK and have access to CIPD, you can use one of these commands to fetch the NDK our bots use:

python2 infra/bots/assets/android_ndk_linux/download.py -t /tmp/ndk
python2 infra/bots/assets/android_ndk_darwin/download.py -t /tmp/ndk
python2 infra/bots/assets/android_ndk_windows/download.py -t C:/ndk

When generating your GN build files, pass the path to your ndk and your desired target_cpu:

bin/gn gen out/arm   --args='ndk="/tmp/ndk" target_cpu="arm"'
bin/gn gen out/arm64 --args='ndk="/tmp/ndk" target_cpu="arm64"'
bin/gn gen out/x64   --args='ndk="/tmp/ndk" target_cpu="x64"'
bin/gn gen out/x86   --args='ndk="/tmp/ndk" target_cpu="x86"'

Other arguments like is_debug and is_component_build continue to work. Tweaking ndk_api gives you access to newer Android features like Vulkan.

To test on an Android device, push the binary and resources over, and run it as normal. You may find bin/droid convenient.

ninja -C out/arm64
adb push out/arm64/dm /data/local/tmp
adb push resources /data/local/tmp
adb shell "cd /data/local/tmp; ./dm --src gm --config gl"

ChromeOS

To cross-compile Skia for arm ChromeOS devices the following is needed:

  • Clang 4 or newer
  • An armhf sysroot
  • The (E)GL lib files on the arm chromebook to link against.

To compile Skia for an x86 ChromeOS device, one only needs Clang and the lib files.

If you have access to CIPD, you can fetch all of these as follows:

python2 infra/bots/assets/clang_linux/download.py  -t /opt/clang
python2 infra/bots/assets/armhf_sysroot/download.py -t /opt/armhf_sysroot
python2 infra/bots/assets/chromebook_arm_gles/download.py -t /opt/chromebook_arm_gles
python2 infra/bots/assets/chromebook_x86_64_gles/download.py -t /opt/chromebook_x86_64_gles

If you don’t have authorization to use those assets, then see the README.md files for armhf_sysrootchromebook_arm_gles, and chromebook_x86_64_gles for instructions on creating those assets.

Once those files are in place, generate the GN args that resemble the following:

#ARM
cc= "/opt/clang/bin/clang"
cxx = "/opt/clang/bin/clang++"

extra_asmflags = [
    "--target=armv7a-linux-gnueabihf",
    "--sysroot=/opt/armhf_sysroot/",
    "-march=armv7-a",
    "-mfpu=neon",
    "-mthumb",
]
extra_cflags=[
    "--target=armv7a-linux-gnueabihf",
    "--sysroot=/opt/armhf_sysroot",
    "-I/opt/chromebook_arm_gles/include",
    "-I/opt/armhf_sysroot/include/",
    "-I/opt/armhf_sysroot/include/c++/4.8.4/",
    "-I/opt/armhf_sysroot/include/c++/4.8.4/arm-linux-gnueabihf/",
    "-DMESA_EGL_NO_X11_HEADERS",
    "-funwind-tables",
]
extra_ldflags=[
    "--sysroot=/opt/armhf_sysroot",
    "-B/opt/armhf_sysroot/bin",
    "-B/opt/armhf_sysroot/gcc-cross",
    "-L/opt/armhf_sysroot/gcc-cross",
    "-L/opt/armhf_sysroot/lib",
    "-L/opt/chromebook_arm_gles/lib",
    "--target=armv7a-linux-gnueabihf",
]
target_cpu="arm"
skia_use_fontconfig = false
skia_use_system_freetype2 = false
skia_use_egl = true


# x86_64
cc= "/opt/clang/bin/clang"
cxx = "/opt/clang/bin/clang++"
extra_cflags=[
    "-I/opt/clang/include/c++/v1/",
    "-I/opt/chromebook_x86_64_gles/include",
    "-DMESA_EGL_NO_X11_HEADERS",
    "-DEGL_NO_IMAGE_EXTERNAL",
]
extra_ldflags=[
    "-stdlib=libc++",
    "-fuse-ld=lld",
    "-L/opt/chromebook_x86_64_gles/lib",
]
target_cpu="x64"
skia_use_fontconfig = false
skia_use_system_freetype2 = false
skia_use_egl = true

Compile dm (or another executable of your choice) with ninja, as per usual.

Push the binary to a chromebook via ssh and run dm as normal using the gles GPU config.

Most chromebooks by default have their home directory partition marked as noexec. To avoid “permission denied” errors, remember to run something like:

sudo mount -i -o remount,exec /home/chronos

Mac

Mac users may want to pass --ide=xcode to bin/gn gen to generate an Xcode project.

iOS

Run GN to generate your build files. Set target_os="ios" to build for iOS. This defaults to target_cpu="arm64". Choosing x64 targets the iOS simulator.

bin/gn gen out/ios64  --args='target_os="ios"'
bin/gn gen out/ios32  --args='target_os="ios" target_cpu="arm"'
bin/gn gen out/iossim --args='target_os="ios" target_cpu="x64"'

This will also package (and for devices, sign) iOS test binaries. This defaults to a Google signing identity and provisioning profile. To use a different one set the GN args skia_ios_identity to match your code signing identity and skia_ios_profile to the name of your provisioning profile, e.g.

skia_ios_identity=".*Jane Doe.*"
skia_ios_profile="iPad Profile"`

A list of identities can be found by typing security find-identity on the command line. The name of the provisioning profile should be available on the Apple Developer site. Alternatively, skia_ios_profile can be the absolute path to the mobileprovision file.

If you find yourself missing a Google signing identity or provisioning profile, you’ll want to have a read through go/appledev.

For signed packages ios-deploy makes installing and running them on a device easy:

ios-deploy -b out/Debug/dm.app -d --args "--match foo"

Alternatively you can generate an Xcode project by passing --ide=xcode to bin/gn gen. If you are using Xcode version 10 or later, you may need to go to Project Settings... and verify that Build System: is set to Legacy Build System.

Deploying to a device with an OS older than the current SDK can be done by setting the ios_min_target arg:

ios_min_target = "<major>.<minor>"

where <major>.<minor> is the iOS version on the device, e.g., 12.0 or 11.4.

Windows

Skia can build on Windows with Visual Studio 2017 or 2019. If GN is unable to locate either of those, it will print an error message. In that case, you can pass your VC path to GN via win_vc.

Skia can be compiled with the free Build Tools for Visual Studio 2017 or 2019.

The bots use a packaged 2019 toolchain, which Googlers can download like this:

python2 infra/bots/assets/win_toolchain/download.py -t C:/toolchain

You can then pass the VC and SDK paths to GN by setting your GN args:

win_vc = "C:\toolchain\VC"
win_sdk = "C:\toolchain\win_sdk"

This toolchain is the only way we support 32-bit builds, by also setting target_cpu="x86".

The Skia build assumes that the PATHEXT environment variable contains “.EXE”.

Skia uses generated code that is only optimized when Skia is built with clang. Other compilers get generic unoptimized code.

Setting the cc and cxx gn args is not sufficient to build with clang-cl. These variables are ignored on Windows. Instead set the variable clang_win to your LLVM installation directory. If you installed the prebuilt LLVM downloaded from here in the default location that would be:

clang_win = "C:\Program Files\LLVM"

Follow the standard Windows path specification and not MinGW convention (e.g. C:\Program Files\LLVM not /c/Program Files/LLVM).

Visual Studio Solutions

If you use Visual Studio, you may want to pass --ide=vs to bin/gn gen to generate all.sln. That solution will exist within the GN directory for the specific configuration, and will only build/run that configuration.

If you want a Visual Studio Solution that supports multiple GN configurations, there is a helper script. It requires that all of your GN directories be inside the out directory. First, create all of your GN configurations as usual. Pass --ide=vs when running bin/gn gen for each one. Then:

python2 gn/gn_meta_sln.py

This creates a new dedicated output directory and solution file out/sln/skia.sln. It has one solution configuration for each GN configuration, and supports building and running any of them. It also adjusts syntax highlighting of inactive code blocks based on preprocessor definitions from the selected solution configuration.

Windows ARM64

There is early, experimental support for Windows 10 on ARM. This currently requires (a recent version of) MSVC, and the Visual C++ compilers and libraries for ARM64 individual component in the Visual Studio Installer. For Googlers, the win_toolchain asset includes the ARM64 compiler.

To use that toolchain, set the target_cpu GN argument to "arm64". Note that OpenGL is not supported by Windows 10 on ARM, so Skia’s GL backends are stubbed out, and will not work. ANGLE is supported:

bin/gn gen out/win-arm64 --args='target_cpu="arm64" skia_use_angle=true'

This will produce a build of Skia that can use the software or ANGLE backends, in DM. Viewer only works when launched with --backend angle, because the software backend tries to use OpenGL to display the window contents.

CMake

We have added a GN-to-CMake translator mainly for use with IDEs that like CMake project descriptions. This is not meant for any purpose beyond development.

bin/gn gen out/config --ide=json --json-ide-script=../../gn/gn_to_cmake.py

 

 

Build canvaskit

https://github.com/google/skia/tree/f88eb656c123cd069f85f9ac1f11007777ce633a/modules/canvaskit

To compile CanvasKit, you will first need to install emscripten. This will set the environment EMSDK (among others) which is required for compilation. Which version should you use? /infra/wasm-common/docker/emsdk-base/Dockerfile shows the version we build and test with. We try to keep this up-to-date.

build通过dockers:

https://github.com/google/skia/tree/master/docker/skia-wasm-release 

posted @ 2021-05-25 17:06  Bigben  阅读(1606)  评论(0编辑  收藏  举报