Skip to content

Commit

Permalink
Compatability Update for Unity 2020+ ToughNutToCrack#19
Browse files Browse the repository at this point in the history
  • Loading branch information
benyaboy committed May 3, 2022
1 parent 7477ff5 commit 4e4d735
Show file tree
Hide file tree
Showing 5 changed files with 241 additions and 27 deletions.
18 changes: 18 additions & 0 deletions Assets/Plugins/WebGL/ARWTAccess.jslib
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
mergeInto(LibraryManager.library, {
CameraReady : function() {
cameraReady();
},
DetectionManagerReady : function () {
detectionManagerReady();
},

ObjectAvailable : function() {
objectAvailable();
},

GetCamName : function(camName) {
var name = Pointer_stringify(camName)
getCamName(name);
},

});
28 changes: 25 additions & 3 deletions Assets/Scripts/Common/CameraController.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
using UnityEngine;
using System.Runtime.InteropServices;

namespace ARWT.Core{
public class CameraController : MonoBehaviour{


[DllImport("__Internal")]
private static extern void ObjectAvailable();

[DllImport("__Internal")]
private static extern void CameraReady();


Matrix4x4 defProj;
Camera cam;

[System.Obsolete]
void Start() {
cam = GetComponent<Camera>();
Application.ExternalCall("cameraReady");

if(!Application.isEditor){
CameraReady();
}

defProj = cam.projectionMatrix;
}
Expand Down Expand Up @@ -93,5 +103,17 @@ public void setEuler(string val){
transform.eulerAngles = new Vector3(x, y, z);
}

public void ObjectCheck(string objectName){

if(GameObject.Find(objectName) != null){
if(!Application.isEditor){
ObjectAvailable();
}
}else{
Debug.LogError("There is no gameobject with the name " + objectName + " available for use!");
}
}


}
}
11 changes: 1 addition & 10 deletions Assets/Scripts/Common/PostBuild/PostBuildActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,18 @@ public class PostBuildActions{
static string markersPath = "data/markers";
static string markersImagesPath = "data/markersImages";
static string index = "index.html";
static string appJS = "js/app.js";



[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string targetPath){
if(PlayerSettings.WebGL.template.Contains("WebAR")){
var path = Path.Combine(targetPath, "Build/UnityLoader.js");
var path = Path.Combine(targetPath, "Build/" + getName(targetPath) + ".loader.js");
var text = File.ReadAllText(path);
text = text.Replace("UnityLoader.SystemInfo.mobile", "false");
File.WriteAllText(path, text);

string buildJsonPath = "Build/" + getName(targetPath) + ".json";
path = Path.Combine(targetPath, "Build/" + getName(targetPath) + ".json");
replaceInFile(path, "backgroundColor", "");

generateHTML(targetPath);
copyImages(targetPath);

string unityDeclaration = $"const unityInstance = UnityLoader.instantiate(\"unityContainer\", \"{buildJsonPath}\");";
replaceInFile(Path.Combine(targetPath, appJS), buildPlaceholder, unityDeclaration);
}
}

Expand Down
9 changes: 7 additions & 2 deletions Assets/Scripts/WebAR/DetectionManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using ARWT.Core;
using UnityEngine;
using System.Runtime.InteropServices;

namespace ARWT.Marker{
public class MarkerInfo{
Expand All @@ -20,14 +21,18 @@ public MarkerInfo(string name, bool isVisible, Vector3 position, Quaternion rota

public class DetectionManager : Singleton<DetectionManager>{

[DllImport("__Internal")]
private static extern void DetectionManagerReady();

public delegate void MarkerDetection(MarkerInfo m);
public static event MarkerDetection onMarkerDetected;
public static event MarkerDetection onMarkerVisible;
public static event MarkerDetection onMarkerLost;

[System.Obsolete]
void Start() {
Application.ExternalCall("detectionManagerReady");
if(!Application.isEditor){
DetectionManagerReady();
}
}

public void markerInfos(string infos){
Expand Down
202 changes: 190 additions & 12 deletions Assets/WebGLTemplates/WebAR/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,201 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | WebGL Test AR</title>
<title>Unity WebGL Player | {{{ PRODUCT_NAME }}}</title>
<script src="Build/{{{ LOADER_FILENAME }}}"></script>
<script src="js/lib/aframe.min.js"></script>
<script src="js/lib/aframe-ar.js"></script>
<script src="Build/UnityLoader.js"></script>
<script src="js/app.js"></script>

</head>
<body>
<!-- style for the loader -->
<style>
html, body {
overflow: hidden;
}

.arjs-loader {
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 1);
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
}

.arjs-loader div {
text-align: center;
font-size: 1.25em;
color: white;
}
</style>

<div class="arjs-loader" id="arjs-loader">
<div>Loading, please wait...</div>
</div>

<div id="unity-container" class="unity-desktop" style="z-index: 2; position: absolute; top: 0; left: 0;">
<canvas id="unity-canvas"></canvas>
</div>

<script>
var container = document.querySelector("#unity-container");
var unityCanvas = document.querySelector("#unity-canvas");

var buildUrl = "Build";
var loaderUrl = buildUrl + "/{{{ LOADER_FILENAME }}}";
var config = {
dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}",
frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}",
codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",
#if MEMORY_FILENAME
memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}",
#endif
#if SYMBOLS_FILENAME
symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}",
#endif
streamingAssetsUrl: "StreamingAssets",
companyName: "{{{ COMPANY_NAME }}}",
productName: "{{{ PRODUCT_NAME }}}",
productVersion: "{{{ PRODUCT_VERSION }}}",
};


var script = document.createElement("script");
var unityInstance;

script.src = loaderUrl;
script.onload = () => {
createUnityInstance(unityCanvas, config, (progress) => {

}).then((ui) => {
unityInstance = ui;

}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);

let isCameraReady = false;
let isDetectionManagerReady = false;
let gl = null;

function cameraReady() {
isCameraReady = true;
gl = unityInstance.Module.ctx;
console.log("Camera Ready");
}

let isObjectAvailable = false;
function objectAvailable() {

isObjectAvailable = true;

}

function detectionManagerReady() {
isDetectionManagerReady = true;
}

let camName = null;
function getCamName(name) {
camName = name;
}

function createUnityMatrix(el) {
const m = el.matrix.clone();
const zFlipped = new THREE.Matrix4().makeScale(1, 1, -1).multiply(m);
const rotated = zFlipped.multiply(new THREE.Matrix4().makeRotationX(-Math.PI / 2));
return rotated;
}

AFRAME.registerComponent('markercontroller', {
schema: {
name: { type: 'string' }
},
tock: function (time, timeDelta) {

let position = new THREE.Vector3();
let rotation = new THREE.Quaternion();
let scale = new THREE.Vector3();

createUnityMatrix(this.el.object3D).decompose(position, rotation, scale);

const serializedInfos = `${this.data.name},${this.el.object3D.visible},${position.toArray()},${rotation.toArray()},${scale.toArray()}`;

if (isDetectionManagerReady) {
unityInstance.SendMessage("DetectionManager", "markerInfos", serializedInfos);
}
}
});

AFRAME.registerComponent('cameratransform', {
tock: function (time, timeDelta) {

let camtr = new THREE.Vector3();
let camro = new THREE.Quaternion();
let camsc = new THREE.Vector3();

this.el.object3D.matrix.clone().decompose(camtr, camro, camsc);

const projection = this.el.components.camera.camera.projectionMatrix.clone();
const serializedProj = `${[...projection.elements]}`

const posCam = `${[...camtr.toArray()]}`
const rotCam = `${[...camro.toArray()]}`

if (isCameraReady) {

setTimeout(() => {
document.querySelector("#arjs-loader").style.display = "none";
}, 1000);

unityInstance.SendMessage(camName, "setProjection", serializedProj);
unityInstance.SendMessage(camName, "setPosition", posCam);
unityInstance.SendMessage(camName, "setRotation", rotCam);

let w = window.innerWidth;
let h = window.innerHeight;

const ratio = unityCanvas.height / h;

w *= ratio;
h *= ratio;

const size = `${w},${h}`;

unityInstance.SendMessage(camName, "ObjectCheck", "Canvas");

if (isObjectAvailable) {
unityInstance.SendMessage("Canvas", "setSize", size);
}
}

if (gl != null) {
gl.dontClearOnFrameStart = true;
}
}
});

AFRAME.registerComponent('copycanvas', {
tick: function (time, timeDelta) {

unityCanvas.style.width = window.innerWidth + 'px';
unityCanvas.style.height = window.innerHeight + 'px';

}
});

</script>

<body style="margin: 0px; overflow: hidden;">
<a-scene embedded arjs vr-mode-ui="enabled: false" copycanvas>
<div id="unityContainer" style="z-index: 2" ></div>
<!-- <a-marker preset="hiro"> <a-box></a-box> </a-marker> -->
<!-- <a-marker type="pattern" url="data/markers/pattern-arjs.patt"><a-box></a-box></a-marker> -->
<!-- <a-marker type="pattern" url="data/markers/test.patt" markercontroller="name : hiro"></a-marker> -->
<a-scene embedded arjs='trackingMethod: best; patternRatio: 0.5; debugUIEnabled: false;' vr-mode-ui="enabled: false" copycanvas>

--MARKERS--
<a-entity camera cameratransform></a-entity>
--MARKERS--
<a-entity camera cameratransform></a-entity>
</a-scene>
</body>
</html>

0 comments on commit 4e4d735

Please sign in to comment.