在javascript中,Array有很多內置的功能,比如Array.map,Array.filter,Array.find等等,能用內置的功能就用內置的功能,最好不要自己實現一套,因為底層調用的可能壓根就不是js語言本身,底層的實現可能由C/C++實現的。如果我們要做的一些功能,需要高性能密集計算,但是JavaScript內置函數無法滿足我們要求的時候,這時候我們就要自己用C/C++編寫一個程序,然后封裝成wasm文件給JavaScript調用了,此時wasm還包含了.a文件這樣的第三方庫。
我們這里有個需求,就是在地球上有兩艘船,船A和船B在某個經緯度位置觸發,以某個航向、速度行駛,求它們間最小距離是多少,達到最小距離的時候,經過時間是多少秒?
首先這個功能用C/C++來編寫,并且還要用到開源第三方庫。
下圖的紅圈注釋里面有幾個參數,分別表示經度、緯度、速度、航向,當然getCPA最后一個參數6.5表示6.5分鐘的時間長度。表示計算6.5分鐘以內,兩船最小距離是多少,并且到達最小距離時,經過時間是多少。
打開Visual Studio 2022,新建一個cmake工程,項目名稱為GeoCompute。這僅僅是一個測試項目,如果測試通過,沒有問題了,就把該代碼交給emcc或者em++去編譯。
CMakeLists.txt文件內容如下:
在這里,我采用vcpkg來安裝GeographicLib庫
可以執行如下命令安裝。
vcpkg install GeographicLib:x64-windows
# CMakeList.txt: GeoCompute 的 CMake 項目,在此處包括源代碼并定義
# 項目特定的邏輯。
#
cmake_minimum_required (VERSION 3.8)
set(VCPKG_ROOT "D:/CppPkg/WinVcpkg/vcpkg" CACHE PATH "")
set(CMAKE_TOOLCHAIN_FILE "${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake")
# Enable Hot Reload for MSVC compilers if supported.
if (POLICY CMP0141)cmake_policy(SET CMP0141 NEW)set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
endif()project ("GeoCompute")# 將源代碼添加到此項目的可執行文件。
add_executable (GeoCompute "GeoCompute.cpp" )find_package (GeographicLib CONFIG REQUIRED)
target_link_libraries (GeoCompute PRIVATE ${GeographicLib_LIBRARIES})if (CMAKE_VERSION VERSION_GREATER 3.12)set_property(TARGET GeoCompute PROPERTY CXX_STANDARD 20)
endif()# TODO: 如有需要,請添加測試并安裝目標。
然后編寫一個GeoCompute.cpp文件
#include <iostream>
#include <GeographicLib/Geodesic.hpp>
#include <GeographicLib/Constants.hpp>
#include <cmath>
#include <vector>const double EARTH_RADIUS = 6377830.0; // 地球的平均半徑,單位為千米
const double M_PI = 3.14159265359;struct LatLon {double first;double second;
};double deg2rad(double deg) {return deg * M_PI / 180.0;
}double haversine_distance(double lat1, double lon1, double lat2, double lon2) {double dlat = deg2rad(lat2 - lat1);double dlon = deg2rad(lon2 - lon1);double a = std::sin(dlat / 2) * std::sin(dlat / 2) +std::cos(deg2rad(lat1)) * std::cos(deg2rad(lat2)) *std::sin(dlon / 2) * std::sin(dlon / 2);double c = 2 * std::atan2(std::sqrt(a), std::sqrt(1 - a));return EARTH_RADIUS * c;
}LatLon new_position_with_geolib(double lat, double lon, double speed, double cog, double T) {const GeographicLib::Geodesic& geod = GeographicLib::Geodesic::WGS84();double s12 = speed * T;double lat2, lon2;// Direct method gives the destination point given start point, initial azimuth, and distancegeod.Direct(lat, lon, cog, s12, lat2, lon2);return { lat2, lon2 };
}double new_distance(double T, double latA, double lonA, double speedA, double cogA, double latB, double lonB, double speedB, double cogB) {auto resA = new_position_with_geolib(latA, lonA, speedA, cogA, T);auto resB = new_position_with_geolib(latB, lonB, speedB, cogB, T);return haversine_distance(resA.first, resA.second, resB.first, resB.second);
}LatLon getCPA(double latA, double lonA, double speedA, double cogA, double latB, double lonB, double speedB, double cogB, double tcpa) {double RES_TCPA = INFINITY;double RES_DCPA = INFINITY;double prev_dist = INFINITY;double cur_dist = INFINITY;std::vector<int> status;int t_lim = tcpa * 60;int step = 1;if (t_lim > 600) {step = int(double(t_lim) / 300.0);}for (int t = 0;t < t_lim; t += step) {prev_dist = new_distance(t, latA, lonA, speedA, cogA, latB, lonB, speedB, cogB);cur_dist = new_distance(t + step, latA, lonA, speedA, cogA, latB, lonB, speedB, cogB);if (prev_dist < RES_DCPA) {RES_DCPA = prev_dist;}if (cur_dist - prev_dist <= 0) {if (status.size() == 0) {status.emplace_back(-1);}}else {if (status.size() == 0) {status.emplace_back(1);break;}else {if (status[0] == -1) {status.emplace_back(1);}}}if (status.size() == 2 && status[0] == -1 && status[1] == 1) {RES_TCPA = t;break;}}return { RES_TCPA, RES_DCPA };
}//1. 一開始距離就變大
// 2. 從0時刻到指定tcpa一直減小
// 3. 從0時刻到指定tcpa,先減小后增大
int main() {double lat = 40, lon = 100, speed = 10, cog = 45, T = 3600;auto result = new_position_with_geolib(lat, lon, speed, cog, T);std::cout << "New Latitude: " << result.first << ", New Longitude: " << result.second << std::endl;/*latA, lonA, speedA, cogA = 21.3058, 109.1014, 15.12, 187.13latB, lonB, speedB, cogB = 21.288205, 109.118725, 3.909777, 254.42*/int i = 0;while (true) {// 先減小后增大auto res_ = getCPA(21.3058, 109.1014, 15.12, 187.13, 21.288205, 109.118725, 3.909777, 254.42, 6.5);//auto res_ = getCPA(22.3058, 108.1014, 15.12, 187.13, 21.288205, 109.118725, 3.909777, 254.42, 6.0);//auto res_ = getCPA(0.0, 0.0, 15.12, 225.0, 0.0000001, 0.0000001, 3.909777, 45.0, 6.0);std::cout << res_.first << " --- " << res_.second << std::endl;i++;printf("%d\n", i);}return 0;
}
好了,如果代碼測試完成了。現在我們創建一個cmake工程,項目名為EmscriptenTest,這是用來生成wasm文件和js文件來給JavaScript調用的。
由于JavaScript運行在瀏覽器,不能直接支持windows的lib靜態庫,所以想辦法得到.a庫。
首先從github拉取geographiclib庫的源碼
git clone https://github.com/geographiclib/geographiclib.git
然后進入到根目錄:
cd geographiclib
最后用emcmake和emmake命令編譯代碼(前提是要安裝emsdk:官網有教程說明:https://emscripten.org/docs/getting_started/downloads.html)
emcmake cmake .
emmake make
編譯完成之后:
轉到目錄geographiclib/src
找到libGeographicLib.a文件,然后把該文件拷貝到EmscriptenTest項目的lib目錄下(如果沒有lib目錄則自己新建)
然后是CMakeLists.txt文件:
# CMakeList.txt: EmscriptenTest 的 CMake 項目,在此處包括源代碼并定義
# 項目特定的邏輯。
#
cmake_minimum_required (VERSION 3.8)
set(CMAKE_TOOLCHAIN_FILE "D:/CppPkg/emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake")
# 手動設置GeographicLib的路徑
set(GEOGRAPHICLIB_INCLUDE_DIR "/path/to/vcpkg/installed/x64-windows/include")
#set(GEOGRAPHICLIB_LIB_DIR "/path/to/vcpkg/installed/x64-windows/lib")
set(GEOGRAPHICLIB_LIB_DIR "填寫你的EmscriptenTest/lib目錄的絕對路徑")# Enable Hot Reload for MSVC compilers if supported.
if (POLICY CMP0141)cmake_policy(SET CMP0141 NEW)set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
endif()project ("EmscriptenTest")# 將源代碼添加到此項目的可執行文件。
add_executable (EmscriptenTest "GeoCompute.cpp")include_directories(D:/CppPkg/WinVcpkg/vcpkg/installed/x64-windows/include )
target_link_libraries(EmscriptenTest ${GEOGRAPHICLIB_LIB_DIR}/libGeographicLib.a)add_library(GeoCompute STATIC GeoCompute.cpp)
set_target_properties(GeoCompute PROPERTIES SUFFIX ".wasm")
set_target_properties(GeoCompute PROPERTIES LINK_FLAGS "--bind -s WASM=1 -s MODULARIZE=1 -s EXPORT_NAME='GeoComputeModule' -s EXPORTED_FUNCTIONS='[\"getCPA\"]'")if (CMAKE_VERSION VERSION_GREATER 3.12)set_property(TARGET EmscriptenTest PROPERTY CXX_STANDARD 20)
endif()# TODO: 如有需要,請添加測試并安裝目標。
這個EmscriptenTest.cpp沒什么用,里面寫個main函數,直接return 0;就完事兒了。
在項目根目錄下新建GeoCompute.cpp文件
GeoCompute.cpp文件的內容:
可能會提示報錯,但是如果點擊重新生成,生成成功的話,是沒事兒的。
在這個文件中,我修改了getCPA函數的返回類型為double* , 因為直接返回TDCPA結構體,JavaScript是無法識別的,一定要返回一個指針。
#include <iostream>
#include <GeographicLib/Geodesic.hpp>
#include <GeographicLib/Constants.hpp>
#include <cmath>
#include <vector>
#include <emscripten/emscripten.h>
const double EARTH_RADIUS = 6377830.0; // 地球的平均半徑,單位為千米
const double _M_PI = 3.14159265359;struct LatLon {double lat;double lon;
};struct TDCPA {double res_tcpa;double res_dcpa;
};extern "C" {EMSCRIPTEN_KEEPALIVEdouble deg2rad(double deg) {return deg * _M_PI / 180.0;}EMSCRIPTEN_KEEPALIVEdouble haversine_distance(double lat1, double lon1, double lat2, double lon2) {double dlat = deg2rad(lat2 - lat1);double dlon = deg2rad(lon2 - lon1);double a = std::sin(dlat / 2) * std::sin(dlat / 2) +std::cos(deg2rad(lat1)) * std::cos(deg2rad(lat2)) *std::sin(dlon / 2) * std::sin(dlon / 2);double c = 2 * std::atan2(std::sqrt(a), std::sqrt(1 - a));return EARTH_RADIUS * c;}EMSCRIPTEN_KEEPALIVELatLon new_position_with_geolib(double lat, double lon, double speed, double cog, double T) {const GeographicLib::Geodesic& geod = GeographicLib::Geodesic::WGS84();double s12 = speed * T;double lat2, lon2;// Direct method gives the destination point given start point, initial azimuth, and distancegeod.Direct(lat, lon, cog, s12, lat2, lon2);return { lat2, lon2 };}EMSCRIPTEN_KEEPALIVEdouble new_distance(double T, double latA, double lonA, double speedA, double cogA, double latB, double lonB, double speedB, double cogB) {auto resA = new_position_with_geolib(latA, lonA, speedA, cogA, T);auto resB = new_position_with_geolib(latB, lonB, speedB, cogB, T);return haversine_distance(resA.lat, resA.lon, resB.lat, resB.lon);}EMSCRIPTEN_KEEPALIVEdouble* getCPA(double latA, double lonA, double speedA, double cogA, double latB, double lonB, double speedB, double cogB, double tcpa) {double RES_TCPA = INFINITY;double RES_DCPA = INFINITY;double prev_dist = INFINITY;double cur_dist = INFINITY;double* tdcpaPtr = new double[2];std::vector<int> status;int t_lim = tcpa * 60;int step = 1;if (t_lim > 600) {step = int(double(t_lim) / 300.0);}for (int t = 0; t < t_lim; t += step) {prev_dist = new_distance(t, latA, lonA, speedA, cogA, latB, lonB, speedB, cogB);cur_dist = new_distance(t + step, latA, lonA, speedA, cogA, latB, lonB, speedB, cogB);if (prev_dist < RES_DCPA) {RES_DCPA = prev_dist;}if (cur_dist - prev_dist <= 0) {if (status.size() == 0) {status.emplace_back(-1);}}else {if (status.size() == 0) {status.emplace_back(1);break;}else {if (status[0] == -1) {status.emplace_back(1);}}}if (status.size() == 2 && status[0] == -1 && status[1] == 1) {RES_TCPA = t;break;}}tdcpaPtr[0] = RES_TCPA;tdcpaPtr[1] = RES_DCPA;return tdcpaPtr;}}
好了,現在就測試全部重新生成。如果沒有報錯,則通過測試。通過測試之后。證明可以大膽使用em++命令直接編譯GeoCompute.cpp為wasm文件了。
打開cmd進入到EmscriptenTest工程根目錄。
em++ GeoCompute.cpp -O1 -o libGeoCompute.js -s WASM=1 -s MODULARIZE=1 -s EXPORT_NAME="GeoComputeModule" -s "EXPORTED_FUNCTIONS=['_deg2rad', '_haversine_distance', '_new_position_with_geolib', '_new_distance', '_getCPA']" -s "EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" -I D:/CppPkg/WinVcpkg/vcpkg/installed/x64-windows/include -L D:/HighPerformanceProjects/CppProjects/EmscriptenTest/lib -lGeographicLib
我這里導出了所有的函數,函數前面要加上下劃線。但是在cmakelists.txt中不需要加下劃線。
執行完成命令之后,會生成libGeoCompute.js和libGeoCompute.wasm文件。
現在可以使用npm創建一個原生的JavaScript項目。
這是工程目錄結構:
最重要是main.js的寫法:
const fs = require('fs');
const path = require('path');// 加載 Emscripten 生成的模塊
const Module = require('./libGeoCompute.js');async function main() {try {const instance = await Module({locateFile: (filename) => path.join(__dirname, filename),});console.log('Module instance:', instance);console.log(typeof instance.cwrap)// await new Promise((resolve) => {// console.log('Waiting for runtime initialization...');// instance.onRuntimeInitialized = () => {// console.log('Runtime initialized.');// resolve();// };// });// 使用 cwrap 包裝 getCPA 函數const getCPA = instance.cwrap('getCPA', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']);console.log(typeof getCPA)// 調用導出的 getCPA 函數const resultPtr = getCPA(21.3058, 109.1014, 15.12, 187.13, 21.288205, 109.118725, 3.909777, 254.42, 6.5);console.log(typeof resultPtr)// 解析返回值(假設返回指向結構體的指針)const res_tcpa = instance.HEAPF64[resultPtr >> 3]; // 讀取double指針的第0個元素const res_dcpa = instance.HEAPF64[(resultPtr >> 3) + 1]; // 讀取地址偏移量+1console.log('TCPA:', res_tcpa);console.log('DCPA:', res_dcpa);console.log('Continuing after runtime initialization.');// 繼續下面的邏輯...} catch (error) {console.error('Error:', error);}
}main();
index.html的內容:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Blank Window</title>
</head>
<body><!-- 這里可以添加窗體的內容 -->
</body>
</html>
package.json的內容:
{"name": "nodedevtest","version": "1.0.0","description": "A minimal Electron application","main": "main.js","scripts": {"start": "node main.js"},"keywords": [],"author": "","license": "ISC","dependencies": {"axios": "^1.6.8","electron": "^30.0.1","pixi.js": "^8.1.0","request": "^2.88.2"}
}
得出的結果:
得出的結果是154和1519.5687501879786
表示經過154秒以后,兩船達到最小距離,并且最小距離為1519米多。