[
  {
    "path": ".gitignore",
    "content": "node_modules\nbuild\ndeploy\nscreens*\nnpm-debug.log\n*.png\n.env\n.DS_Store\n"
  },
  {
    "path": "README.md",
    "content": "# Multiple Window 3D Scene using Three.js\n\n## Introduction\nThis project demonstrates a unique approach to creating and managing a 3D scene across multiple browser windows using Three.js and localStorage. It's designed for developers interested in advanced web graphics and window management techniques.\n\n## Features\n- 3D scene creation and rendering with Three.js.\n- Synchronization of 3D scenes across multiple browser windows.\n- Dynamic window management and state synchronization using localStorage.\n\n## Installation\nClone the repository and open `index.html` in your browser to start exploring the 3D scene.\n\n```\ngit clone https://github.com/bgstaal/multipleWindow3dScene\n```\n## Usage\nThe main application logic is contained within `main.js` and `WindowManager.js`. The 3D scene is rendered in `index.html`, which serves as the entry point of the application.\n\n## Structure and Components\n- `index.html`: Entry point that sets up the HTML structure and includes the Three.js library and the main script.\n- `WindowManager.js`: Core class managing window creation, synchronization, and state management across multiple windows.\n- `main.js`: Contains the logic for initializing the 3D scene, handling window events, and rendering the scene.\n- `three.r124.min.js`: Minified version of the Three.js library used for 3D graphics rendering.\n\n## Detailed Functionality\n- `WindowManager.js` handles the lifecycle of multiple browser windows, including creation, synchronization, and removal. It uses localStorage to maintain state across windows.\n- `main.js` initializes the 3D scene using Three.js, manages the window's resize events, and updates the scene based on window interactions.\n\n## Contributing\nContributions to enhance or expand the project are welcome. Feel free to fork the repository, make changes, and submit pull requests.\n\n## License\nThis project is open-sourced under the MIT License.\n\n## Acknowledgments\n- The Three.js team for their comprehensive 3D library.\n- x.com/didntdrinkwater for this readme.\n\n## Contact\nFor more information and updates, follow [@_nonfigurativ_](https://twitter.com/_nonfigurativ_) on Twitter.\n"
  },
  {
    "path": "WindowManager.js",
    "content": "class WindowManager \n{\n\t#windows;\n\t#count;\n\t#id;\n\t#winData;\n\t#winShapeChangeCallback;\n\t#winChangeCallback;\n\t\n\tconstructor ()\n\t{\n\t\tlet that = this;\n\n\t\t// event listener for when localStorage is changed from another window\n\t\taddEventListener(\"storage\", (event) => \n\t\t{\n\t\t\tif (event.key == \"windows\")\n\t\t\t{\n\t\t\t\tlet newWindows = JSON.parse(event.newValue);\n\t\t\t\tlet winChange = that.#didWindowsChange(that.#windows, newWindows);\n\n\t\t\t\tthat.#windows = newWindows;\n\n\t\t\t\tif (winChange)\n\t\t\t\t{\n\t\t\t\t\tif (that.#winChangeCallback) that.#winChangeCallback();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// event listener for when current window is about to ble closed\n\t\twindow.addEventListener('beforeunload', function (e) \n\t\t{\n\t\t\tlet index = that.getWindowIndexFromId(that.#id);\n\n\t\t\t//remove this window from the list and update local storage\n\t\t\tthat.#windows.splice(index, 1);\n\t\t\tthat.updateWindowsLocalStorage();\n\t\t});\n\t}\n\n\t// check if theres any changes to the window list\n\t#didWindowsChange (pWins, nWins)\n\t{\n\t\tif (pWins.length != nWins.length)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlet c = false;\n\n\t\t\tfor (let i = 0; i < pWins.length; i++)\n\t\t\t{\n\t\t\t\tif (pWins[i].id != nWins[i].id) c = true;\n\t\t\t}\n\n\t\t\treturn c;\n\t\t}\n\t}\n\n\t// initiate current window (add metadata for custom data to store with each window instance)\n\tinit (metaData)\n\t{\n\t\tthis.#windows = JSON.parse(localStorage.getItem(\"windows\")) || [];\n\t\tthis.#count= localStorage.getItem(\"count\") || 0;\n\t\tthis.#count++;\n\n\t\tthis.#id = this.#count;\n\t\tlet shape = this.getWinShape();\n\t\tthis.#winData = {id: this.#id, shape: shape, metaData: metaData};\n\t\tthis.#windows.push(this.#winData);\n\n\t\tlocalStorage.setItem(\"count\", this.#count);\n\t\tthis.updateWindowsLocalStorage();\n\t}\n\n\tgetWinShape ()\n\t{\n\t\tlet shape = {x: window.screenLeft, y: window.screenTop, w: window.innerWidth, h: window.innerHeight};\n\t\treturn shape;\n\t}\n\n\tgetWindowIndexFromId (id)\n\t{\n\t\tlet index = -1;\n\n\t\tfor (let i = 0; i < this.#windows.length; i++)\n\t\t{\n\t\t\tif (this.#windows[i].id == id) index = i;\n\t\t}\n\n\t\treturn index;\n\t}\n\n\tupdateWindowsLocalStorage ()\n\t{\n\t\tlocalStorage.setItem(\"windows\", JSON.stringify(this.#windows));\n\t}\n\n\tupdate ()\n\t{\n\t\t//console.log(step);\n\t\tlet winShape = this.getWinShape();\n\n\t\t//console.log(winShape.x, winShape.y);\n\n\t\tif (winShape.x != this.#winData.shape.x ||\n\t\t\twinShape.y != this.#winData.shape.y ||\n\t\t\twinShape.w != this.#winData.shape.w ||\n\t\t\twinShape.h != this.#winData.shape.h)\n\t\t{\n\t\t\t\n\t\t\tthis.#winData.shape = winShape;\n\n\t\t\tlet index = this.getWindowIndexFromId(this.#id);\n\t\t\tthis.#windows[index].shape = winShape;\n\n\t\t\t//console.log(windows);\n\t\t\tif (this.#winShapeChangeCallback) this.#winShapeChangeCallback();\n\t\t\tthis.updateWindowsLocalStorage();\n\t\t}\n\t}\n\n\tsetWinShapeChangeCallback (callback)\n\t{\n\t\tthis.#winShapeChangeCallback = callback;\n\t}\n\n\tsetWinChangeCallback (callback)\n\t{\n\t\tthis.#winChangeCallback = callback;\n\t}\n\n\tgetWindows ()\n\t{\n\t\treturn this.#windows;\n\t}\n\n\tgetThisWindowData ()\n\t{\n\t\treturn this.#winData;\n\t}\n\n\tgetThisWindowID ()\n\t{\n\t\treturn this.#id;\n\t}\n}\n\nexport default WindowManager;"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<title>3d example using three.js and multiple windows</title>\n\t<script type=\"text/javascript\" src=\"three.r124.min.js\"></script>\n\t<style type=\"text/css\">\n\t\t\n\t\t*\n\t\t{\n\t\t\tmargin: 0;\n\t\t\tpadding: 0;\n\t\t}\n\n\t</style>\n</head>\n<body>\n\t\n\t<script type=\"module\" src=\"main.js\"></script>\n</body>\n</html>"
  },
  {
    "path": "main.js",
    "content": "import WindowManager from './WindowManager.js'\n\n\n\nconst t = THREE;\nlet camera, scene, renderer, world;\nlet near, far;\nlet pixR = window.devicePixelRatio ? window.devicePixelRatio : 1;\nlet cubes = [];\nlet sceneOffsetTarget = {x: 0, y: 0};\nlet sceneOffset = {x: 0, y: 0};\n\nlet today = new Date();\ntoday.setHours(0);\ntoday.setMinutes(0);\ntoday.setSeconds(0);\ntoday.setMilliseconds(0);\ntoday = today.getTime();\n\nlet internalTime = getTime();\nlet windowManager;\nlet initialized = false;\n\n// get time in seconds since beginning of the day (so that all windows use the same time)\nfunction getTime ()\n{\n\treturn (new Date().getTime() - today) / 1000.0;\n}\n\n\nif (new URLSearchParams(window.location.search).get(\"clear\"))\n{\n\tlocalStorage.clear();\n}\nelse\n{\t\n\t// this code is essential to circumvent that some browsers preload the content of some pages before you actually hit the url\n\tdocument.addEventListener(\"visibilitychange\", () => \n\t{\n\t\tif (document.visibilityState != 'hidden' && !initialized)\n\t\t{\n\t\t\tinit();\n\t\t}\n\t});\n\n\twindow.onload = () => {\n\t\tif (document.visibilityState != 'hidden')\n\t\t{\n\t\t\tinit();\n\t\t}\n\t};\n\n\tfunction init ()\n\t{\n\t\tinitialized = true;\n\n\t\t// add a short timeout because window.offsetX reports wrong values before a short period \n\t\tsetTimeout(() => {\n\t\t\tsetupScene();\n\t\t\tsetupWindowManager();\n\t\t\tresize();\n\t\t\tupdateWindowShape(false);\n\t\t\trender();\n\t\t\twindow.addEventListener('resize', resize);\n\t\t}, 500)\t\n\t}\n\n\tfunction setupScene ()\n\t{\n\t\tcamera = new t.OrthographicCamera(0, 0, window.innerWidth, window.innerHeight, -10000, 10000);\n\t\t\n\t\tcamera.position.z = 2.5;\n\t\tnear = camera.position.z - .5;\n\t\tfar = camera.position.z + 0.5;\n\n\t\tscene = new t.Scene();\n\t\tscene.background = new t.Color(0.0);\n\t\tscene.add( camera );\n\n\t\trenderer = new t.WebGLRenderer({antialias: true, depthBuffer: true});\n\t\trenderer.setPixelRatio(pixR);\n\t    \n\t  \tworld = new t.Object3D();\n\t\tscene.add(world);\n\n\t\trenderer.domElement.setAttribute(\"id\", \"scene\");\n\t\tdocument.body.appendChild( renderer.domElement );\n\t}\n\n\tfunction setupWindowManager ()\n\t{\n\t\twindowManager = new WindowManager();\n\t\twindowManager.setWinShapeChangeCallback(updateWindowShape);\n\t\twindowManager.setWinChangeCallback(windowsUpdated);\n\n\t\t// here you can add your custom metadata to each windows instance\n\t\tlet metaData = {foo: \"bar\"};\n\n\t\t// this will init the windowmanager and add this window to the centralised pool of windows\n\t\twindowManager.init(metaData);\n\n\t\t// call update windows initially (it will later be called by the win change callback)\n\t\twindowsUpdated();\n\t}\n\n\tfunction windowsUpdated ()\n\t{\n\t\tupdateNumberOfCubes();\n\t}\n\n\tfunction updateNumberOfCubes ()\n\t{\n\t\tlet wins = windowManager.getWindows();\n\n\t\t// remove all cubes\n\t\tcubes.forEach((c) => {\n\t\t\tworld.remove(c);\n\t\t})\n\n\t\tcubes = [];\n\n\t\t// add new cubes based on the current window setup\n\t\tfor (let i = 0; i < wins.length; i++)\n\t\t{\n\t\t\tlet win = wins[i];\n\n\t\t\tlet c = new t.Color();\n\t\t\tc.setHSL(i * .1, 1.0, .5);\n\n\t\t\tlet s = 100 + i * 50;\n\t\t\tlet cube = new t.Mesh(new t.BoxGeometry(s, s, s), new t.MeshBasicMaterial({color: c , wireframe: true}));\n\t\t\tcube.position.x = win.shape.x + (win.shape.w * .5);\n\t\t\tcube.position.y = win.shape.y + (win.shape.h * .5);\n\n\t\t\tworld.add(cube);\n\t\t\tcubes.push(cube);\n\t\t}\n\t}\n\n\tfunction updateWindowShape (easing = true)\n\t{\n\t\t// storing the actual offset in a proxy that we update against in the render function\n\t\tsceneOffsetTarget = {x: -window.screenX, y: -window.screenY};\n\t\tif (!easing) sceneOffset = sceneOffsetTarget;\n\t}\n\n\n\tfunction render ()\n\t{\n\t\tlet t = getTime();\n\n\t\twindowManager.update();\n\n\n\t\t// calculate the new position based on the delta between current offset and new offset times a falloff value (to create the nice smoothing effect)\n\t\tlet falloff = .05;\n\t\tsceneOffset.x = sceneOffset.x + ((sceneOffsetTarget.x - sceneOffset.x) * falloff);\n\t\tsceneOffset.y = sceneOffset.y + ((sceneOffsetTarget.y - sceneOffset.y) * falloff);\n\n\t\t// set the world position to the offset\n\t\tworld.position.x = sceneOffset.x;\n\t\tworld.position.y = sceneOffset.y;\n\n\t\tlet wins = windowManager.getWindows();\n\n\n\t\t// loop through all our cubes and update their positions based on current window positions\n\t\tfor (let i = 0; i < cubes.length; i++)\n\t\t{\n\t\t\tlet cube = cubes[i];\n\t\t\tlet win = wins[i];\n\t\t\tlet _t = t;// + i * .2;\n\n\t\t\tlet posTarget = {x: win.shape.x + (win.shape.w * .5), y: win.shape.y + (win.shape.h * .5)}\n\n\t\t\tcube.position.x = cube.position.x + (posTarget.x - cube.position.x) * falloff;\n\t\t\tcube.position.y = cube.position.y + (posTarget.y - cube.position.y) * falloff;\n\t\t\tcube.rotation.x = _t * .5;\n\t\t\tcube.rotation.y = _t * .3;\n\t\t};\n\n\t\trenderer.render(scene, camera);\n\t\trequestAnimationFrame(render);\n\t}\n\n\n\t// resize the renderer to fit the window size\n\tfunction resize ()\n\t{\n\t\tlet width = window.innerWidth;\n\t\tlet height = window.innerHeight\n\t\t\n\t\tcamera = new t.OrthographicCamera(0, width, 0, height, -10000, 10000);\n\t\tcamera.updateProjectionMatrix();\n\t\trenderer.setSize( width, height );\n\t}\n}"
  },
  {
    "path": "three-LICENSE",
    "content": "The MIT License\n\nCopyright © 2010-2023 three.js authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE."
  }
]