Adding support for custom background images

This change adds support for custom background images.

Usage:
- Background images are stored in "backgrounds" folder as with jpg or png.
- Both 360 degree (equirectangular) and 6-side cubemap images are supported. This is automatically detected based on aspect ratio (with cubemap having 4:3 aspect ratio).
- Select the background from Settings.

Changes:
- The selected background image is persisted in config in this format: "background": "backgrounds/my_background.jpg",
- Image is decoded in a background thread (via Android plugin), as Texture2D.LoadImage can cause multi-second freeze on the UI thread. We then compensate for unity (re-ordering coordinate origin and also alpha channel).
- Made ground smaller & semi-transparent
This commit is contained in:
tverona1
2019-09-14 18:07:34 -07:00
parent 30fbb2afb6
commit 4f0399bcdf
22 changed files with 3016 additions and 148 deletions
+8 -7
View File
@@ -9,12 +9,13 @@ Material:
m_PrefabAsset: {fileID: 0}
m_Name: GroundMat
m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords: _EMISSION
m_ShaderKeywords: _ALPHAPREMULTIPLY_ON _EMISSION
m_LightmapFlags: 1
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
@@ -59,19 +60,19 @@ Material:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _DstBlend: 10
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _Mode: 3
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
- _ZWrite: 0
m_Colors:
- _Color: {r: 0.2509804, g: 0.2627451, b: 0.29803923, a: 1}
- _Color: {r: 0.2509804, g: 0.28235295, b: 0.39607844, a: 0.57254905}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
+60
View File
@@ -19,6 +19,8 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Calendar;
import java.util.Map;
import java.util.zip.ZipEntry;
@@ -27,7 +29,9 @@ import java.util.zip.ZipOutputStream;
import android.os.Bundle;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Color;
import java.util.List;
import java.util.LinkedList;
@@ -36,6 +40,12 @@ class AppInfoInternal {
public long lastTimeUsed;
}
class DecodedBitmap {
int width;
int height;
byte[] rawImage;
}
public class AppInfo extends UnityPlayerActivity {
private static final String TAG = "AppInfo";
@@ -263,6 +273,56 @@ public class AppInfo extends UnityPlayerActivity {
}
}
public static DecodedBitmap loadRawImage(String imagePath, int maxWidth, int maxHeight) {
Log.v(TAG, "Decoding image at " + imagePath);
try {
// Decode bitmap with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
// Calculate inSampleSize
int height = options.outHeight;
int width = options.outWidth;
Log.v(TAG, "Image dimensions: " + height + "x" + width);
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width smaller than the requested height and width.
options.inSampleSize = 1;
while ((height / options.inSampleSize) >= maxHeight
|| (width / options.inSampleSize) >= maxWidth) {
options.inSampleSize *= 2;
}
Log.v(TAG, "Image sample size: " + options.inSampleSize);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.inPremultiplied = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPreferQualityOverSpeed = true;
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
if (null == bmp) {
Log.v(TAG, "Failed to decode image at " + imagePath);
return null;
}
DecodedBitmap decodedBmp = new DecodedBitmap();
decodedBmp.width = bmp.getWidth();
decodedBmp.height = bmp.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(bmp.getByteCount());
bmp.copyPixelsToBuffer(byteBuffer);
decodedBmp.rawImage = byteBuffer.array();
Log.v(TAG, "Done decoding image at " + imagePath);
return decodedBmp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void createDirIfNotExist(File path) {
if (!path.exists()) {
path.mkdirs();
+4
View File
@@ -398,8 +398,12 @@ MonoBehaviour:
m_Name:
m_EditorClassIdentifier:
sprite: {fileID: 4032891918720229799}
text: {fileID: 6771208205116626490}
packageId:
appName:
externalIconPath:
installedApkIndex: 0
isRenameMode: 0
--- !u!1 &5252017818009209086
GameObject:
m_ObjectHideFlags: 0
+309
View File
@@ -0,0 +1,309 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &2718414468714522334
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3876971168137039905}
- component: {fileID: 7606802177034282429}
- component: {fileID: 6771208205116626490}
m_Layer: 0
m_Name: Name
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &3876971168137039905
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2718414468714522334}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 2187993270055489575}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &7606802177034282429
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2718414468714522334}
m_CullTransparentMesh: 0
--- !u!114 &6771208205116626490
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2718414468714522334}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: f4688fdb7df04437aeb418b961361dc5, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
m_text:
m_isRightToLeft: 0
m_fontAsset: {fileID: 11400000, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2}
m_sharedMaterial: {fileID: 2180264, guid: 8f586378b4e144a9851e7b34d9b748ee, type: 2}
m_fontSharedMaterials: []
m_fontMaterial: {fileID: 0}
m_fontMaterials: []
m_fontColor32:
serializedVersion: 2
rgba: 4294967295
m_fontColor: {r: 1, g: 1, b: 1, a: 1}
m_enableVertexGradient: 0
m_colorMode: 3
m_fontColorGradient:
topLeft: {r: 1, g: 1, b: 1, a: 1}
topRight: {r: 1, g: 1, b: 1, a: 1}
bottomLeft: {r: 1, g: 1, b: 1, a: 1}
bottomRight: {r: 1, g: 1, b: 1, a: 1}
m_fontColorGradientPreset: {fileID: 0}
m_spriteAsset: {fileID: 0}
m_tintAllSprites: 0
m_overrideHtmlColors: 0
m_faceColor:
serializedVersion: 2
rgba: 4294967295
m_outlineColor:
serializedVersion: 2
rgba: 4278190080
m_fontSize: 36
m_fontSizeBase: 36
m_fontWeight: 400
m_enableAutoSizing: 0
m_fontSizeMin: 18
m_fontSizeMax: 96
m_fontStyle: 1
m_textAlignment: 514
m_characterSpacing: 0
m_wordSpacing: 0
m_lineSpacing: 0
m_lineSpacingMax: 0
m_paragraphSpacing: 0
m_charWidthMaxAdj: 0
m_enableWordWrapping: 1
m_wordWrappingRatios: 0.4
m_overflowMode: 0
m_firstOverflowCharacterIndex: -1
m_linkedTextComponent: {fileID: 0}
m_isLinkedTextComponent: 0
m_isTextTruncated: 0
m_enableKerning: 1
m_enableExtraPadding: 0
checkPaddingRequired: 0
m_isRichText: 1
m_parseCtrlCharacters: 1
m_isOrthographic: 1
m_isCullingEnabled: 0
m_ignoreRectMaskCulling: 0
m_ignoreCulling: 1
m_horizontalMapping: 0
m_verticalMapping: 0
m_uvLineOffset: 0
m_geometrySortingOrder: 0
m_VertexBufferAutoSizeReduction: 1
m_firstVisibleCharacter: 0
m_useMaxVisibleDescender: 1
m_pageToDisplay: 1
m_margin: {x: 0, y: 0, z: 0, w: 0}
m_textInfo:
textComponent: {fileID: 6771208205116626490}
characterCount: 0
spriteCount: 0
spaceCount: 0
wordCount: 0
linkCount: 0
lineCount: 0
pageCount: 0
materialCount: 1
m_isUsingLegacyAnimationComponent: 0
m_isVolumetricText: 0
m_spriteAnimator: {fileID: 0}
m_hasFontAssetChanged: 0
m_subTextObjects:
- {fileID: 0}
- {fileID: 0}
- {fileID: 0}
- {fileID: 0}
- {fileID: 0}
- {fileID: 0}
- {fileID: 0}
- {fileID: 0}
m_baseMaterial: {fileID: 0}
m_maskOffset: {x: 0, y: 0, z: 0, w: 0}
--- !u!1 &4824380111246446992
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2187993270055489575}
- component: {fileID: 4582160310205455797}
- component: {fileID: 5153811987148017347}
- component: {fileID: 4106709632587049678}
m_Layer: 0
m_Name: SkyboxEntry
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &2187993270055489575
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4824380111246446992}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 3876971168137039905}
- {fileID: 3061537210812862376}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &4582160310205455797
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4824380111246446992}
m_CullTransparentMesh: 0
--- !u!65 &5153811987148017347
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4824380111246446992}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 780, y: 60, z: 0.06}
m_Center: {x: 0, y: 0, z: 0}
--- !u!114 &4106709632587049678
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4824380111246446992}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6e773b6a61a5a604388f69b6f343f8db, type: 3}
m_Name:
m_EditorClassIdentifier:
text: {fileID: 6771208205116626490}
path:
--- !u!1 &5252017818009209086
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3061537210812862376}
- component: {fileID: 165040609097649856}
- component: {fileID: 8280379170912847942}
m_Layer: 0
m_Name: Border
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!224 &3061537210812862376
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5252017818009209086}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 2187993270055489575}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &165040609097649856
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5252017818009209086}
m_CullTransparentMesh: 0
--- !u!114 &8280379170912847942
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5252017818009209086}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 0.14097543, g: 0.8301887, b: 0.22752704, a: 0.8117647}
m_RaycastTarget: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
m_Sprite: {fileID: 21300000, guid: b6bb78fcd6b3a574191fd2967990903b, type: 3}
m_Type: 1
m_PreserveAspect: 0
m_FillCenter: 0
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8da3d69c2a551d241a0760dd57d7a671
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
+6
View File
@@ -1,11 +1,17 @@
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class AppEntry : MonoBehaviour
{
// Sprite gameobject
public GameObject sprite;
// TMP text
public TextMeshProUGUI text;
// App entry contents
public string packageId;
public string appName;
public string externalIconPath;
+6
View File
@@ -28,6 +28,9 @@ namespace QuestAppLauncher
public const string DownloadRepo_Type_GitHub = "github";
public const string DownloadRepo_Default = @"tverona1/QuestAppLauncher_Assets/releases/latest";
// Background
public const string Background_Default = "default";
/// <summary>
/// Grid size
/// </summary>
@@ -66,6 +69,9 @@ namespace QuestAppLauncher
// Whether to auto-download updates
public bool autoUpdate = false;
// Background image path
public string background = Background_Default;
// Github download repos
public List<DownloadRepo> downloadRepos = new List<DownloadRepo>();
+11 -3
View File
@@ -34,6 +34,9 @@ namespace QuestAppLauncher
// Scroll container game object
public GameObject scrollContainer;
// SKybox handler
public SkyboxHandler skyboxHandler;
// Tab containers
public GameObject topTabContainer;
public GameObject leftTabContainer;
@@ -101,6 +104,12 @@ namespace QuestAppLauncher
// Load configuration
var config = ConfigPersistence.LoadConfig();
// Set skybox
if (!isRenameMode)
{
this.skyboxHandler.SetSkybox(config.background);
}
// Process apps in background
var apps = await Task.Run(() =>
{
@@ -377,7 +386,7 @@ namespace QuestAppLauncher
var newObj = (GameObject)Instantiate(this.prefabCell, transform);
// Set app entry info
var appEntry = newObj.GetComponent("AppEntry") as AppEntry;
var appEntry = newObj.GetComponent<AppEntry>();
appEntry.packageId = app.PackageName;
appEntry.appName = app.AppName;
appEntry.isRenameMode = isRenameMode;
@@ -401,8 +410,7 @@ namespace QuestAppLauncher
}
// Set app name in text
var text = newObj.transform.Find("AppName").GetComponentInChildren<TextMeshProUGUI>();
text.text = app.AppName;
appEntry.text.text = app.AppName;
}
}
#endregion
+27
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
@@ -21,7 +22,9 @@ namespace QuestAppLauncher
public GameObject gridPopulation;
public GameObject show2DToggle;
public GameObject autoUpdateToggle;
public GameObject skyBoxButton;
public DownloadStatusIndicator downloadStatusIndicator;
public SkyboxHandler skyboxHandler;
public Toggle tabsAutoOff;
public Toggle tabsAutoTop;
@@ -57,6 +60,9 @@ namespace QuestAppLauncher
// Load config
this.config = ConfigPersistence.LoadConfig();
// Skybox callback
this.skyboxHandler.OnSkyboxSelected = OnSkyboxSelected;
// Set current cols & rows
var colsSlider = this.gridCols.GetComponent<Slider>();
colsSlider.value = this.config.gridSize.cols;
@@ -75,6 +81,9 @@ namespace QuestAppLauncher
// Set 2D toggle
this.show2DToggle.GetComponent<Toggle>().SetIsOnWithoutNotify(this.config.show2D);
// Set skybox button text
this.skyBoxButton.GetComponentInChildren<TextMeshProUGUI>().text = SkyboxHandler.GetSkyboxNameFromPath(this.config.background);
// Set auto-update toggle
this.autoUpdateToggle.GetComponent<Toggle>().SetIsOnWithoutNotify(this.config.autoUpdate);
@@ -142,6 +151,19 @@ namespace QuestAppLauncher
}
}
public void OnSkyboxSelected(string skyboxPath)
{
// Update text
this.skyBoxButton.GetComponentInChildren<TextMeshProUGUI>().text = SkyboxHandler.GetSkyboxNameFromPath(skyboxPath);
// Save config with new skybox selection
if (!this.config.background.Equals(skyboxPath, StringComparison.OrdinalIgnoreCase))
{
this.config.background = skyboxPath;
ConfigPersistence.SaveConfig(this.config);
}
}
public void DeleteRenameFiles()
{
Debug.Log("Delete Rename files");
@@ -166,6 +188,11 @@ namespace QuestAppLauncher
rowsText.text = string.Format("{0} Rows", rows);
}
public void ShowSkyboxList()
{
this.skyboxHandler.ShowList();
}
private bool HasUsageStatsPermissions()
{
// Check if we have UsageStats permission
+13
View File
@@ -0,0 +1,13 @@
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class SkyboxEntry : MonoBehaviour
{
// TMP text
public TextMeshProUGUI text;
// Relative path to skybox
public string path;
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6e773b6a61a5a604388f69b6f343f8db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+383
View File
@@ -0,0 +1,383 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using TMPro;
using UnityEngine;
namespace QuestAppLauncher
{
public class SkyboxHandler : MonoBehaviour
{
// Max width and height of skybox image.
// Anything larger we'll scale down. We restrict it primarily due to memory constraints.
const int MaxWidth = 4096;
const int MaxHeight = 4096;
// Skybox selected callback
public Action<string> OnSkyboxSelected;
// Skyview List Container
public GameObject skyviewListContainer;
// Skybox list entry prefab
public GameObject prefabSkyboxEntry;
// Content transform
public Transform contentTransform;
// Default skybox
private Material defaultSkybox;
// Skybox folder
private const string SkyboxFolder = "backgrounds";
// Extension search for images
const string JpgExtSearch = "*.jpg";
const string PngExtSearch = "*.png";
/// <summary>
/// Show the skybox list dialog
/// </summary>
public async void ShowList()
{
// Show the dialog
this.skyviewListContainer.SetActive(true);
// Populate the list
await PopulateAsync();
}
public void OnCancel()
{
// Hide the dialog
this.skyviewListContainer.SetActive(false);
}
public void OnHoverEnter(Transform t)
{
var appEntry = t.gameObject.GetComponent("SkyboxEntry") as SkyboxEntry;
if (null != appEntry)
{
// Enable border
EnableBorder(t, true);
}
}
public void OnHoverExit(Transform t)
{
var appEntry = t.gameObject.GetComponent("SkyboxEntry") as SkyboxEntry;
if (null != appEntry)
{
// Disable border
EnableBorder(t, false);
}
}
public async void OnSelected(Transform t)
{
var entry = t.gameObject.GetComponent("SkyboxEntry") as SkyboxEntry;
if (null != entry)
{
// Set the skybox
SetSkybox(entry.path);
this.skyviewListContainer.SetActive(false);
// Callback if registered
if (null != OnSkyboxSelected)
{
OnSkyboxSelected(entry.path);
}
}
}
/// <summary>
/// Return skybox name given its path (i.e. filename w/o extension)
/// </summary>
/// <param name="skyboxPath">Path to skybox image</param>
/// <returns></returns>
public static string GetSkyboxName(string skyboxPath)
{
try
{
return Path.GetFileNameWithoutExtension(skyboxPath);
}
catch (Exception e)
{
Debug.LogFormat("Error trying to get filename of skybox: {0} ({1})", skyboxPath, e.Message);
}
// Fall back to default
return Config.Background_Default;
}
/// <summary>
/// Sets the skybox. Supports either equirectangular or cubemap, auto chosen based on aspect ratio.
/// </summary>
/// <param name="skyboxPath">Path to skybox image</param>
/// <returns></returns>
public async Task SetSkybox(string skyboxPath)
{
Debug.LogFormat("Setting skybox to '{0}'", skyboxPath);
if (null == this.defaultSkybox)
{
// Save off the default skybox
this.defaultSkybox = RenderSettings.skybox;
}
if (IsDefaultSkybox(skyboxPath))
{
if (RenderSettings.skybox == this.defaultSkybox)
{
// Skip if skybox is already the default
Debug.LogFormat("Skybox already default, skipping.");
return;
}
// Set default skybox
SetDefaultSkybox();
return;
}
// Read the image
int imageHeight = 0;
int imageWidth = 0;
var image = await Task.Run(() =>
{
AndroidJNI.AttachCurrentThread();
try
{
using (AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using (AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity"))
{
// Call Android plugin to load the raw image.
var jo = currentActivity.CallStatic<AndroidJavaObject>("loadRawImage", MakeAbsoluteSkymapPath(skyboxPath), MaxHeight, MaxWidth);
if (null == jo)
{
return null;
}
// Get the width, height and raw image data.
imageWidth = jo.Get<int>("width");
imageHeight = jo.Get<int>("height");
var rawImage = (byte[])(Array)jo.Get<sbyte[]>("rawImage");
// The image is in ARGB_8888 format (Alpha, Red, Green, Blue - each 1 byte). In addition, (0, 0) coordinates are bottom-left.
// Unity expects RGBA (with Alpha as the last byte) and origin at top-left. So we need to compensate for both.
// Shift alpha
for (var i = 0; i < rawImage.Length / 4; i++)
{
var tmp = rawImage[i * 4 + 3];
rawImage[i * 4 + 3] = rawImage[i * 4 + 2];
rawImage[i * 4 + 2] = rawImage[i * 4 + 1];
rawImage[i * 4 + 1] = rawImage[i * 4];
rawImage[i * 4] = tmp;
}
// Swap rows
var row = new byte[imageWidth * 4];
for (var i = 0; i < imageHeight / 2; i++)
{
Buffer.BlockCopy(rawImage, i * imageWidth * 4, row, 0, imageWidth * 4);
Buffer.BlockCopy(rawImage, (imageHeight - i - 1) * imageWidth * 4, rawImage, i * imageWidth * 4, imageWidth * 4);
Buffer.BlockCopy(row, 0, rawImage, (imageHeight - i - 1) * imageWidth * 4, imageWidth * 4);
}
return rawImage;
}
}
catch (Exception e)
{
// Fall back to using the apk icon
Debug.LogFormat("Error decoding image [{0}]: {1}", skyboxPath, e.Message);
return null;
}
finally
{
AndroidJNI.DetachCurrentThread();
}
});
if (null == image)
{
// Fall back to default skybox
SetDefaultSkybox();
return;
}
try
{
// Load the image into a 2D texture. We decode in background thread (above) in Java and load the raw image here
// because Texture2D.LoadImage on the main thread can cause significant freezes since it is not async.
var texture = new Texture2D(imageWidth, imageHeight, TextureFormat.ARGB32, false);
texture.filterMode = FilterMode.Trilinear;
texture.anisoLevel = 16;
texture.LoadRawTextureData(image);
texture.Apply();
Material material;
if (4 * texture.height == 3 * texture.width)
{
// Texture is a cube map (4:3 aspect ratio).
// Load cubemap shader. Also rotate x-axis by 180 degrees to compensate for platform-specific rendering differences
// (see https://docs.unity3d.com/Manual/SL-PlatformDifferences.html).
Debug.LogFormat("Setting cubemap skybox");
material = new Material(Shader.Find("skybox/cube"));
material.SetFloat("_RotationX", 180);
material.SetTexture("_Tex", CubemapFromTexture2D(texture));
}
else
{
// Texture is equirectangular
Debug.LogFormat("Setting equirectangular skybox");
material = new Material(Shader.Find("skybox/equirectangular"));
material.SetTexture("_Tex", texture);
}
RenderSettings.skybox = material;
DynamicGI.UpdateEnvironment();
}
catch (Exception e)
{
// Fall back to default skybox
Debug.LogFormat("Exception: {0}", e.Message);
SetDefaultSkybox();
}
}
/// <summary>
/// Gets cubemap from a 2D texture (which represents 6-sided cube)
/// </summary>
/// <param name="texture"></param>
/// <returns></returns>
private static Cubemap CubemapFromTexture2D(Texture2D texture)
{
int cubedim = texture.width / 4;
Cubemap cube = new Cubemap(cubedim, TextureFormat.ARGB32, false);
cube.SetPixels(texture.GetPixels(0, cubedim, cubedim, cubedim), CubemapFace.NegativeX);
cube.SetPixels(texture.GetPixels(cubedim, cubedim, cubedim, cubedim), CubemapFace.PositiveZ);
cube.SetPixels(texture.GetPixels(2 * cubedim, cubedim, cubedim, cubedim), CubemapFace.PositiveX);
cube.SetPixels(texture.GetPixels(3 * cubedim, cubedim, cubedim, cubedim), CubemapFace.NegativeZ);
cube.SetPixels(texture.GetPixels(cubedim, 0, cubedim, cubedim), CubemapFace.PositiveY);
cube.SetPixels(texture.GetPixels(cubedim, 2 * cubedim, cubedim, cubedim), CubemapFace.NegativeY);
cube.Apply();
return cube;
}
public void SetDefaultSkybox()
{
Debug.LogFormat("Setting default skybox");
RenderSettings.skybox = this.defaultSkybox;
DynamicGI.UpdateEnvironment();
}
/// <summary>
/// Populates the list of skybox images available for pick from
/// </summary>
/// <returns></returns>
private async Task PopulateAsync()
{
// Get list of skyboxes in background
var skyboxes = await Task.Run(() =>
{
return EnumerateSkyboxFiles();
});
// Clear existing list
foreach (Transform child in this.contentTransform)
{
GameObject.Destroy(child.gameObject);
}
// Populate list of skyboxes
foreach(var skybox in skyboxes.OrderBy(key => key.Key))
{
var newObj = (GameObject)Instantiate(this.prefabSkyboxEntry, this.contentTransform);
var entry = newObj.GetComponent<SkyboxEntry>();
entry.text.text = skybox.Key;
entry.path = skybox.Value;
}
}
/// <summary>
/// Construct map of backgrond name -> path
/// </summary>
/// <returns>Returned map</returns>
private Dictionary<string, string> EnumerateSkyboxFiles()
{
var skyboxes = new Dictionary<string, string>();
// Add default
skyboxes[Config.Background_Default] = Config.Background_Default;
// Enumerate jpg files
foreach (var filePath in Directory.GetFiles(
GetOrCreateSkymapPath(), JpgExtSearch))
{
skyboxes[Path.GetFileNameWithoutExtension(filePath)] = MakeRelativeSkymapPath(filePath);
}
// Enumerate png files
foreach (var filePath in Directory.GetFiles(
GetOrCreateSkymapPath(), PngExtSearch))
{
skyboxes[Path.GetFileNameWithoutExtension(filePath)] = MakeRelativeSkymapPath(filePath);
}
return skyboxes;
}
private void EnableBorder(Transform t, bool enable)
{
var border = t.Find("Border");
border?.gameObject.SetActive(enable);
}
static private string GetOrCreateSkymapPath()
{
string path = Path.Combine(UnityEngine.Application.persistentDataPath, SkyboxFolder);
Directory.CreateDirectory(path);
return path;
}
static private string MakeRelativeSkymapPath(string path)
{
return path.Substring(UnityEngine.Application.persistentDataPath.Length + 1);
}
static private string MakeAbsoluteSkymapPath(string path)
{
return Path.Combine(UnityEngine.Application.persistentDataPath, path);
}
static public bool IsDefaultSkybox(string path)
{
return Config.Background_Default.Equals(path, StringComparison.OrdinalIgnoreCase);
}
static public string GetSkyboxNameFromPath(string path)
{
if (IsDefaultSkybox(path))
{
return Config.Background_Default;
}
try
{
return Path.GetFileNameWithoutExtension(path);
}
catch (Exception e)
{
// Fall back to default
Debug.LogFormat("Error trying to get filename of path: {0} ({1})", path, e.Message);
}
return Config.Background_Default;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 30eacec5c6a73a14894eea6fafe7a53a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 726d81a23d411f7499ccbe375f149915
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+97
View File
@@ -0,0 +1,97 @@
Shader "skybox/cube" {
Properties {
_Tint ("Tint Color", Color) = (.5, .5, .5, .5)
[Gamma] _Exposure ("Exposure", Range(0, 8)) = 1.0
_RotationX ("RotationX", Range(0, 360)) = 0
_RotationY ("RotationY", Range(0, 360)) = 0
_RotationZ ("RotationZ", Range(0, 360)) = 0
[NoScaleOffset] _Tex ("Cubemap (HDR)", Cube) = "grey" {}
}
SubShader {
Tags { "Queue"="Background" "RenderType"="Background" "PreviewType"="Skybox" }
Cull Off ZWrite Off
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
samplerCUBE _Tex;
half4 _Tex_HDR;
half4 _Tint;
half _Exposure;
float _RotationX;
float _RotationY;
float _RotationZ;
float3 RotateAroundXInDegrees (float3 vertex, float degrees)
{
float alpha = degrees * UNITY_PI / 180.0;
float sina, cosa;
sincos(alpha, sina, cosa);
float2x2 m = float2x2(cosa, -sina, sina, cosa);
return float3(vertex.x, mul(m, vertex.yz)).xyz; //yzx
}
float3 RotateAroundYInDegrees (float3 vertex, float degrees)
{
float alpha = degrees * UNITY_PI / 180.0;
float sina, cosa;
sincos(alpha, sina, cosa);
float2x2 m = float2x2(cosa, -sina, sina, cosa);
return float3(mul(m, vertex.xz), vertex.y).xzy;
}
float3 RotateAroundZInDegrees (float3 vertex, float degrees)
{
float alpha = degrees * UNITY_PI / 180.0;
float sina, cosa;
sincos(alpha, sina, cosa);
float2x2 m = float2x2(cosa, -sina, sina, cosa);
return float3(mul(m, vertex.xy), vertex.z).zxy;
}
struct appdata_t {
float4 vertex : POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f {
float4 vertex : SV_POSITION;
float3 texcoord : TEXCOORD0;
UNITY_VERTEX_OUTPUT_STEREO
};
v2f vert (appdata_t v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
// Only rotate on X-axis. Can add othere axes later if needed.
float3 rotated = RotateAroundXInDegrees(v.vertex, _RotationX);
o.vertex = UnityObjectToClipPos(rotated);
o.texcoord = v.vertex.xyz;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half4 tex = texCUBE (_Tex, i.texcoord);
half3 c = DecodeHDR (tex, _Tex_HDR);
c = c * _Tint.rgb * unity_ColorSpaceDouble.rgb;
c *= _Exposure;
return half4(c, 1);
}
ENDCG
}
}
Fallback Off
}
+9
View File
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 9b9fb5719097baa4ea45fe71d1241070
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
+72
View File
@@ -0,0 +1,72 @@
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "skybox/equirectangular" {
Properties {
_Tint ("Tint Color", Color) = (.5, .5, .5, .5)
[Gamma] _Exposure ("Exposure", Range(0, 8)) = 1.0
_Rotation ("Rotation", Range(0, 360)) = 0
[NoScaleOffset] _Tex ("Panorama (HDR)", 2D) = "grey" {}
}
SubShader {
Tags { "Queue"="Background" "RenderType"="Background" "PreviewType"="Skybox" }
Cull Off ZWrite Off
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _Tex;
half4 _Tex_HDR;
half4 _Tint;
half _Exposure;
float _Rotation;
float4 RotateAroundYInDegrees (float4 vertex, float degrees)
{
float alpha = degrees * UNITY_PI / 180.0;
float sina, cosa;
sincos(alpha, sina, cosa);
float2x2 m = float2x2(cosa, -sina, sina, cosa);
return float4(mul(m, vertex.xz), vertex.yw).xzyw;
}
struct appdata_t {
float4 vertex : POSITION;
};
struct v2f {
float4 vertex : SV_POSITION;
float3 texcoord : TEXCOORD0;
};
v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(RotateAroundYInDegrees(v.vertex, _Rotation));
o.texcoord = v.vertex.xyz;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float3 dir = normalize(i.texcoord);
float2 longlat = float2(atan2(dir.x, dir.z) + UNITY_PI, acos(-dir.y));
float2 uv = longlat / float2(2.0 * UNITY_PI, UNITY_PI);
half4 tex = tex2D (_Tex, uv);
half3 c = DecodeHDR (tex, _Tex_HDR);
c = c * _Tint.rgb * unity_ColorSpaceDouble.rgb;
c *= _Exposure;
return half4(c, 1);
}
ENDCG
}
}
Fallback Off
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: ee5d41dde463f084da6749a67e1f4c18
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+115
View File
@@ -0,0 +1,115 @@
fileFormatVersion: 2
guid: b6bb78fcd6b3a574191fd2967990903b
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 2
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 0
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 4, y: 4, z: 4, w: 4}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
+3
View File
@@ -39,6 +39,9 @@ GraphicsSettings:
- {fileID: 16001, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 16003, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 17000, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 4800000, guid: ee5d41dde463f084da6749a67e1f4c18, type: 3}
- {fileID: 4800000, guid: 9b9fb5719097baa4ea45fe71d1241070, type: 3}
- {fileID: 108, guid: 0000000000000000f000000000000000, type: 0}
m_PreloadedShaders: []
m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
type: 0}