Skip to content

Commit

Permalink
chore: add webgl template
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew-yangy committed Oct 8, 2024
1 parent e0c61d3 commit 87a9d15
Show file tree
Hide file tree
Showing 19 changed files with 602 additions and 19 deletions.
33 changes: 15 additions & 18 deletions sample/Assets/Scripts/SelectAuthMethodScript.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@ public class SelectAuthMethodScript : MonoBehaviour
[SerializeField] private Text Output;
[SerializeField] private Button UseDeviceCodeAuthButton;
[SerializeField] private Button UsePKCEButton;
string REDIRECT_URI = null;
string LOGOUT_REIDIRECT_URI = "https://www.immutable.com";
string redirectUri = null;
string logoutRedirectUri = "https://www.immutable.com";
string clientId = "ZJL7JvetcDFBNDlgRs5oJoxuAUUl6uQj";
#pragma warning restore CS8618
void Start()
{
#if UNITY_WEBGL
string url = Application.absoluteURL;
Uri uri = new Uri(url);
string scheme = uri.Scheme;
string hostWithPort = uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
string fullPath = uri.AbsolutePath.EndsWith("/") ? uri.AbsolutePath : uri.AbsolutePath.Substring(0, uri.AbsolutePath.LastIndexOf('/') + 1);
string url = Application.absoluteURL;
Uri uri = new Uri(url);
string scheme = uri.Scheme;
string hostWithPort = uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
string fullPath = uri.AbsolutePath.EndsWith("/") ? uri.AbsolutePath : uri.AbsolutePath.Substring(0, uri.AbsolutePath.LastIndexOf('/') + 1);

REDIRECT_URI = $"{scheme}://{hostWithPort}{fullPath}callback.html";
LOGOUT_REIDIRECT_URI = $"{scheme}://{hostWithPort}{fullPath}logout.html";
redirectUri = $"{scheme}://{hostWithPort}{fullPath}callback.html";
logoutRedirectUri = $"{scheme}://{hostWithPort}{fullPath}logout.html";
clientId = "UnB98ngnXIZIEJWGJOjVe1BpCx5ix7qc";
#endif

// Determine if PKCE is supported based on the platform
Expand All @@ -34,7 +36,7 @@ void Start()
// If PKCE is not supported, initialise Passport to use Device Code Auth
if (!SampleAppManager.SupportsPKCE)
{
InitialisePassport(redirectUri: REDIRECT_URI, logoutRedirectUri: LOGOUT_REIDIRECT_URI);
InitialisePassport();
}
}

Expand All @@ -56,7 +58,7 @@ private bool IsPKCESupported()
public void UseDeviceCodeAuth()
{
SampleAppManager.UsePKCE = false;
InitialisePassport(redirectUri: REDIRECT_URI, logoutRedirectUri: LOGOUT_REIDIRECT_URI);
InitialisePassport();
}

/// <summary>
Expand All @@ -65,17 +67,13 @@ public void UseDeviceCodeAuth()
public void UsePKCE()
{
SampleAppManager.UsePKCE = true;
InitialisePassport(redirectUri: REDIRECT_URI, logoutRedirectUri: LOGOUT_REIDIRECT_URI);
InitialisePassport();
}

/// <summary>
/// Initialises Passport.
/// </summary>
/// <param name="redirectUri">(Android, iOS and macOS only) The URL to which auth will redirect the browser after
/// authorisation has been granted by the user</param>
/// <param name="logoutRedirectUri">The URL to which auth will redirect the browser
/// after log out is complete</param>
private async void InitialisePassport(string redirectUri = null, string logoutRedirectUri = null)
private async void InitialisePassport()
{
ShowOutput("Initialising Passport...");

Expand All @@ -85,7 +83,6 @@ private async void InitialisePassport(string redirectUri = null, string logoutRe
Passport.LogLevel = LogLevel.Info;

// Initialise Passport
string clientId = "ZJL7JvetcDFBNDlgRs5oJoxuAUUl6uQj";
string environment = Immutable.Passport.Model.Environment.SANDBOX;

Passport passport = await Passport.Init(clientId, environment, redirectUri, logoutRedirectUri);
Expand Down
351 changes: 351 additions & 0 deletions sample/Assets/WebGLTemplates/unity-webview/Passport/index.html

Large diffs are not rendered by default.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions sample/Assets/WebGLTemplates/unity-webview/TemplateData/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
body { padding: 0; margin: 0 }
#unity-container { position: absolute }
#unity-container.unity-desktop { left: 50%; top: 50%; transform: translate(-50%, -50%) }
#unity-container.unity-mobile { position: fixed; width: 100%; height: 100% }
#unity-canvas { background: {{{ BACKGROUND_COLOR }}} }
.unity-mobile #unity-canvas { width: 100%; height: 100% }
#unity-loading-bar { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); display: none }
#unity-logo { width: 154px; height: 130px; background: url('unity-logo-{{{ SPLASH_SCREEN_STYLE.toLowerCase() }}}.png') no-repeat center }
#unity-progress-bar-empty { width: 141px; height: 18px; margin-top: 10px; margin-left: 6.5px; background: url('progress-bar-empty-{{{ SPLASH_SCREEN_STYLE.toLowerCase() }}}.png') no-repeat center }
#unity-progress-bar-full { width: 0%; height: 18px; margin-top: 10px; background: url('progress-bar-full-{{{ SPLASH_SCREEN_STYLE.toLowerCase() }}}.png') no-repeat center }
#unity-footer { position: relative }
.unity-mobile #unity-footer { display: none }
#unity-webgl-logo { float:left; width: 204px; height: 38px; background: url('webgl-logo.png') no-repeat center }
#unity-build-title { float: right; margin-right: 10px; line-height: 38px; font-family: arial; font-size: 18px }
#unity-fullscreen-button { cursor:pointer; float: right; width: 38px; height: 38px; background: url('fullscreen-button.png') no-repeat center }
#unity-warning { position: absolute; left: 50%; top: 5%; transform: translate(-50%); background: white; padding: 10px; display: none }
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions sample/Assets/WebGLTemplates/unity-webview/callback.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | Immutable Runner</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="unity-webview.js"></script>
</head>
<body>
<div id="unity-container" class="unity-desktop">
<div id="unity-build-title">Logging in</div>
</div>
<script>
window.opener.postMessage({
type: 'callback',
url: window.location.href,
});
window.close();
</script>
</body>
</html>
99 changes: 99 additions & 0 deletions sample/Assets/WebGLTemplates/unity-webview/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | Immutable Runner</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="unity-webview.js"></script>
</head>
<body>
<div id="unity-container" class="unity-desktop">
<canvas id="unity-canvas"></canvas>
<div id="unity-loading-bar">
<div id="unity-logo"></div>
<div id="unity-progress-bar-empty">
<div id="unity-progress-bar-full"></div>
</div>
</div>
<div id="unity-footer">
<div id="unity-webgl-logo"></div>
<div id="unity-fullscreen-button"></div>
<div id="unity-build-title">Immutable Runner</div>
</div>
</div>
<script>
var buildUrl = "Build";
var loaderUrl = buildUrl + "/webgl.loader.js";
var config = {
dataUrl: buildUrl + "/webgl.data",
frameworkUrl: buildUrl + "/webgl.framework.js",
codeUrl: buildUrl + "/webgl.wasm",
streamingAssetsUrl: "StreamingAssets",
companyName: "Immutable",
productName: "Immutable Runner",
productVersion: "0.1.0",
};

var container = document.querySelector("#unity-container");
var canvas = document.querySelector("#unity-canvas");
var loadingBar = document.querySelector("#unity-loading-bar");
var progressBarFull = document.querySelector("#unity-progress-bar-full");
var fullscreenButton = document.querySelector("#unity-fullscreen-button");
var width0 = "960px";
var height0 = "600px";

if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
container.className = "unity-mobile";
config.devicePixelRatio = 1;
} else {
canvas.style.width = "960px";
canvas.style.height = "600px";
}
loadingBar.style.display = "block";

document.addEventListener(
'fullscreenchange',
function() {
var p = document.getElementById('unity-container');
var c = document.getElementById('unity-canvas');
if (document.fullscreenElement) {
width0 = c.style.width;
height0 = c.style.height;
setTimeout(
function() {
c.style.width = getComputedStyle(p).width;
c.style.height = getComputedStyle(p).height;
},
250);
} else {
c.style.width = width0;
c.style.height = height0;
}
});
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
window.unityInstance = unityInstance;
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
var p = document.getElementById('unity-container');
var c = document.getElementById('unity-canvas');
c.requestFullscreen = () => {
p.requestFullscreen();
};
unityInstance.SetFullscreen(1);
};
}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);
</script>
</body>
</html>
24 changes: 24 additions & 0 deletions sample/Assets/WebGLTemplates/unity-webview/logout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | Immutable Runner</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="unity-webview.js"></script>
</head>
<body>
<div id="unity-container" class="unity-desktop">
<div id="unity-build-title">Logging out</div>
</div>
<script>
window.opener.postMessage({
type: 'logout',
url: window.location.href,
});
window.close();
</script>
</body>
</html>
72 changes: 72 additions & 0 deletions sample/Assets/WebGLTemplates/unity-webview/unity-webview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
var unityWebView =
{
loaded: [],

init: function(name) {
$containers = $('.webviewContainer');
if ($containers.length === 0) {
$('<div style="position: absolute; left: 0px; width: 100%; height: 100%; top: 0px; pointer-events: none;"><div class="webviewContainer" style="overflow: hidden; position: relative; width: 100%; height: 100%; z-index: 1;"></div></div>')
.appendTo($('#unity-container'));
}
var $last = $('.webviewContainer:last');
var clonedTop = parseInt($last.css('top')) - 100;
var $clone = $last.clone().insertAfter($last).css('top', clonedTop + '%');
var $iframe =
$('<iframe style="position:relative; width:100%; height100%; border-style:none; display:none; pointer-events:auto;"></iframe>')
.attr('id', 'webview_' + name)
.appendTo($last)
$iframe.on('load', function () {
$(this).attr('loaded', 'true');

var js = `window.Unity = {
call:function(msg) {
parent.unityWebView.sendMessage('${name}', msg);
}
};`;

this.contentWindow.eval(js);

window.addEventListener('message', function(event) {
if ((event.data.type === 'callback' || event.data.type === 'logout') && event.isTrusted) {
unityInstance.SendMessage(name, 'CallOnAuth', event.data.url);
}
}, false);
});
return $iframe;
},

sendMessage: function (name, message) {
unityInstance.SendMessage(name, "CallFromJS", message);
},

loadURL: function(name, url) {
var baseUrl = window.location.origin + window.location.pathname.replace(/\/[^\/]*$/, "");
console.log(url, window.location.origin, window.location.pathname);
console.log(baseUrl);
const host = window.location.origin.includes('localhost') ? window.location.origin : baseUrl;
this.iframe(name).attr('loaded', 'false')[0].contentWindow.location.replace(host + url);
},

evaluateJS: function (name, js) {
$iframe = this.iframe(name);
if ($iframe.attr('loaded') === 'true') {
$iframe[0].contentWindow.eval(js);
} else {
$iframe.on('load', function(){
$(this)[0].contentWindow.eval(js);
});
}
},

destroy: function (name) {
this.iframe(name).parent().parent().remove();
},

iframe: function (name) {
return $('#webview_' + name);
},

launchAuthURL: function(name, url) {
window.open(url, '_blank', 'width=460,height=660');
},
};
2 changes: 1 addition & 1 deletion sample/ProjectSettings/ProjectSettings.asset
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,7 @@ PlayerSettings:
webGLTemplate: PROJECT:unity-webview
webGLAnalyzeBuildSize: 0
webGLUseEmbeddedResources: 0
webGLCompressionFormat: 2
webGLCompressionFormat: 0
webGLWasmArithmeticExceptions: 0
webGLLinkerTarget: 1
webGLThreadsSupport: 0
Expand Down

0 comments on commit 87a9d15

Please sign in to comment.