game.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. import * as THREE from 'three'
  2. import gsap from 'gsap'
  3. import { Howl, Howler } from 'howler'
  4. import LevelLoader from './library/levelloader.js'
  5. import { loadGltf } from './library/loadgltf.js'
  6. import { loadRgbeBackground } from './library/loadbackground.js'
  7. import { getForwardVector, getRightVector, drawDebugLine } from './library/mathhelpers.js'
  8. import Ingredient from './library/ingredient.js'
  9. import './library/arrayhelpers.js'
  10. // Shaders
  11. import firefliesVertex from './shaders/firefly/vertex.glsl'
  12. import firefliesFragment from './shaders/firefly/fragment.glsl'
  13. import cauldronVertex from './shaders/cauldron/vertex.glsl'
  14. import cauldronFragment from './shaders/cauldron/fragment.glsl'
  15. // UI
  16. import { brewTutorialPrompt, closeMainMenuUI, mainMenuUI, openMainMenuUI } from './ui/mainmenuui.js'
  17. import { brewUI, openBrewUI, closeBrewUI, updateIngredients } from './ui/gameui.js'
  18. import { closeShopUI, openShopUI, shopTutorialPrompt, shopUI } from './ui/shopui.js'
  19. import { navigationUI, hideNavigationUI, nextRoom, previousRoom } from './ui/navigationui.js'
  20. // Game Data
  21. import * as levelData from './data/level.json'
  22. import * as ingredientInfo from './data/ingredients.json'
  23. import * as potionInfo from './data/potions.json'
  24. import Shopper from './shopper.js'
  25. import { buildCanvasText } from './library/canvastext.js'
  26. import { hideGameStatusUI, updateGameStatusUI } from './ui/gamestatusui.js'
  27. import { gameOverUI, showGameOverUI } from './ui/gameoverui.js'
  28. import { closeMarketUI, marketUI, openMarketUI } from './ui/marketui.js'
  29. import { creditsUI, hideCreditsUI } from './ui/creditsui.js'
  30. import { hideOptionsUI, optionsUI } from './ui/optionsui.js'
  31. export const GAME_SAVE_KEY = "spookonomics-v1"
  32. const raycast = new THREE.Raycaster()
  33. let game, jackolantern, doorway, directionalLight, doorway2, lollipop, candle, candleLit, book
  34. const ingredients = []
  35. const soundEffects = {}
  36. const stageData = {}
  37. export const ROOM_SHOP = 1;
  38. export const ROOM_BREW = 2;
  39. export const ROOM_MARKET = 3;
  40. const shelfSlots = [
  41. { "position": new THREE.Vector3(-3.5, 1.5, -3.5), "motionPath": [{ x: -3, y: 1.3, z: -3.5 }, { x: -1.5, y: 2, z: 0 }, { x: -0.5, y: 2, z: 0 }, { x: 0, y: 0.5, z: 0 }] },
  42. { "position": new THREE.Vector3(-4.5, 1.5, -3.5), "motionPath": [{ x: -3, y: 1.3, z: -3.5 }, { x: -1.5, y: 2, z: 0 }, { x: -0.5, y: 2, z: 0 }, { x: 0, y: 0.5, z: 0 }] },
  43. { "position": new THREE.Vector3(-4.5, 0, -3.0), "motionPath": [{ x: -3, y: 1.3, z: -3.5 }, { x: -1.5, y: 2, z: 0 }, { x: -0.5, y: 2, z: 0 }, { x: 0, y: 0.5, z: 0 }] },
  44. { "position": new THREE.Vector3(-3.3, 3, -3.5), "motionPath": [{ x: -3, y: 1.3, z: -3.5 }, { x: -1.5, y: 2, z: 0 }, { x: -0.5, y: 2, z: 0 }, { x: 0, y: 0.5, z: 0 }] }
  45. ]
  46. const storeShelfSlots = [
  47. { "position": new THREE.Vector3(-12.5, 2.75, -3.25), "motionPath": [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }] },
  48. { "position": new THREE.Vector3(-11.5, 2.75, -3.25), "motionPath": [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }] },
  49. { "position": new THREE.Vector3(-8.5, 2.75, -3.25), "motionPath": [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }] },
  50. { "position": new THREE.Vector3(-7.5, 2.75, -3.25), "motionPath": [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }] },
  51. { "position": new THREE.Vector3(-8.5, 1.25, -3.25), "motionPath": [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }] },
  52. { "position": new THREE.Vector3(-7.5, 1.25, -3.25), "motionPath": [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }] },
  53. ]
  54. const customerSlots = [
  55. { "position": new THREE.Vector3(-12.9, 0.1, 3) },
  56. { "position": new THREE.Vector3(-13.1, 0.1, 4) },
  57. { "position": new THREE.Vector3(-12.7, 0.1, 5) },
  58. { "position": new THREE.Vector3(-13.1, 0.1, 6) },
  59. { "position": new THREE.Vector3(-12.9, 0.1, 7) },
  60. { "position": new THREE.Vector3(-13, 0.1, 8) },
  61. ]
  62. const bubblePositions = []
  63. const bubbleVelocity = []
  64. const bubbleLifespan = []
  65. const bubbleScale = []
  66. const bubbleCount = 15
  67. async function beginBrew(game, stageData) {
  68. if (!stageData.potionToBrew) {
  69. stageData.soundEffects['audio/witch_cackle1.ogg'].play()
  70. return
  71. }
  72. const newInventory = [...stageData.ingredientInventory]
  73. newInventory.remove(stageData.selectedIngredients[0])
  74. newInventory.remove(stageData.selectedIngredients[1])
  75. if(stageData.ingredientInventory.length - newInventory.length < 2) {
  76. stageData.soundEffects['audio/witch_cackle1.ogg'].play()
  77. return
  78. }
  79. stageData.cauldron.isBrewing = true
  80. closeBrewUI(game, stageData)
  81. stageData.brewWitch.stir = true
  82. stageData.brewWitch.bounce = true
  83. stageData.spoon.visible = true
  84. stageData.selectedIngredients.forEach(ingredientName => {
  85. ingredients.find((ingredient => ingredient.getName() == ingredientName)).beginBrew()
  86. })
  87. stageData.bottle1 = await loadGltf(game, stageData.potionToBrew.model)
  88. stageData.bottle1.position.y = -1.5
  89. game.scene.add(stageData.bottle1)
  90. stageData.soundEffects['audio/click1.ogg'].play()
  91. const nextColorData = stageData.potionToBrew.color
  92. stageData.cauldronUniforms.uNextPotionColor.value = new THREE.Color(nextColorData.r, nextColorData.g, nextColorData.b)
  93. stageData.cauldronUniforms.uBlendTime.value = 0.0
  94. setTimeout(() => {
  95. stageData.soundEffects['audio/bubbling.mp3'].play()
  96. stageData.bubbleParticles.visible = true
  97. gsap.to(stageData.cauldronUniforms.uBlendTime, {
  98. value: 1, duration: 4.5, onComplete: () => {
  99. stageData.cauldronUniforms.uPotionColor.value = stageData.cauldronUniforms.uNextPotionColor.value
  100. stageData.cauldronUniforms.uBlendTime.value = 0.0
  101. }
  102. })
  103. }, 900)
  104. setTimeout(() => {
  105. addValueToSave(stageData.potionInventory, 'potion-inventory', stageData.potionToBrew.name)
  106. removeValueFromSave(stageData.ingredientInventory, 'ingredient-inventory', stageData.selectedIngredients[0])
  107. removeValueFromSave(stageData.ingredientInventory, 'ingredient-inventory', stageData.selectedIngredients[1])
  108. stageData.potionToBrew = null
  109. stageData.selectedIngredients = []
  110. stageData.bottle1.position.set(0, -1.5, 0)
  111. stageData.soundEffects['audio/bubbling.mp3'].fade(1, 0, 300).on('fade', () => {
  112. stageData.soundEffects['audio/bubbling.mp3'].stop()
  113. stageData.soundEffects['audio/bubbling.mp3'].volume(0.5)
  114. })
  115. stageData.brewWitch.stir = false
  116. stageData.brewWitch.bounce = false
  117. stageData.spoon.visible = false
  118. stageData.bubbleParticles.visible = false
  119. updateIngredients(game, stageData)
  120. gsap.to(stageData.bottle1.position, {
  121. duration: 3, y: 1.5, ease: "elastic", onComplete: () => {
  122. setTimeout(() => {
  123. game.scene.remove(stageData.bottle1)
  124. //TODO play potion particle effect
  125. stageData.cauldron.isBrewing = false
  126. }, 1000)
  127. }
  128. })
  129. }, 5000)
  130. }
  131. async function customerBuilder(randomPotion, delay) {
  132. const shopperPosition = customerSlots[stageData.customers.length].position
  133. const randomIndex = Math.floor(Math.random() * 3)
  134. let shopper
  135. switch (randomIndex) {
  136. case 0:
  137. shopper = new Shopper(game, 'characters/assembled_character_1.gltf.glb', randomPotion, new THREE.Vector3(3.5, 3.5, 3.5), shopperPosition, Math.PI, function (elapsedTime) {
  138. this.object3d.position.y = 0.0625 * Math.sin(2 * elapsedTime) + 0.5
  139. })
  140. break;
  141. case 1:
  142. shopper = new Shopper(game, 'characters/character_skeleton_minion.gltf', randomPotion, new THREE.Vector3(1, 1, 1), shopperPosition, Math.PI, function (elapsedTime) {
  143. this.object3d.scale.x = 1 + (0.03125 * Math.sin(11.8 * elapsedTime))
  144. this.object3d.scale.y = 1 + (-0.03125 * Math.sin(11.8 * elapsedTime))
  145. this.object3d.scale.z = 1 + (0.03125 * Math.sin(11.8 * elapsedTime))
  146. })
  147. break;
  148. case 2:
  149. shopper = new Shopper(game, 'characters/ghost_1.gltf.glb', randomPotion, new THREE.Vector3(3.5, 3.5, 3.5), shopperPosition, Math.PI, function (elapsedTime) {
  150. this.object3d.position.y = 0.0625 * Math.sin(2.2 * elapsedTime) + 0.5
  151. })
  152. break;
  153. }
  154. await shopper.init(delay)
  155. return shopper
  156. }
  157. export function sellTutorialPrompt(stageData) {
  158. if(stageData.shopTutorial2.alreadySeen) {
  159. return
  160. }
  161. stageData.shopInactivityHandle = setTimeout(() => {
  162. gsap.to(stageData.shopTutorial2.material, {duration: 1.5, opacity: 1, onStart: () => {
  163. stageData.shopTutorial2.castShadow = true
  164. }})
  165. }, 5000)
  166. }
  167. async function beginSell(game, stageData) {
  168. if (stageData.potionStocked.length < 1) {
  169. stageData.soundEffects['audio/witch_cackle1.ogg'].play()
  170. return
  171. }
  172. stageData.soundEffects['audio/click1.ogg'].play()
  173. stageData.isSellingPotions = true
  174. sellTutorialPrompt(stageData)
  175. let randomPotions = []
  176. randomPotions.push(...stageData.potionStocked)
  177. randomPotions.push(...stageData.potionInventory)
  178. randomPotions.push(...stageData.potionInfo.map(info => info.name))
  179. randomPotions.shuffle()
  180. let numberOfCustomers = Math.min(randomPotions.length, Math.floor(Math.random() * 3) + 3)
  181. for (let i = 0; i < numberOfCustomers; i++) {
  182. const desiredPotion = randomPotions.shift()
  183. const potionInfo = stageData.potionInfo.find(info => info.name == desiredPotion)
  184. stageData.customers.push(await customerBuilder(potionInfo, i))
  185. }
  186. setTimeout(() => {
  187. stageData.soundEffects['audio/store-entrance-bell.ogg'].play()
  188. }, 500)
  189. stageData.customers[0].showDesire()
  190. closeShopUI(game, stageData)
  191. }
  192. export async function updatePotionShelfDisplay() {
  193. let storeShelfSpot = 0
  194. for (let i = 0; i < storeShelfSlots.length; i++) {
  195. if (stageData.displayedPotions[i]) {
  196. game.entities.remove(stageData.displayedPotions[i])
  197. game.scene.remove(stageData.displayedPotions[i])
  198. stageData.displayedPotions[i] = null
  199. }
  200. const currentPotionInfo = stageData.potionInfo.find(potion => stageData.potionStocked[i] == potion.name)
  201. if (!currentPotionInfo) {
  202. continue
  203. }
  204. const currentPotion = await loadGltf(game, currentPotionInfo.model)
  205. currentPotion.position.copy(storeShelfSlots[storeShelfSpot++].position)
  206. currentPotion.potionData = currentPotionInfo
  207. stageData.displayedPotions[i] = currentPotion
  208. game.entities.push(currentPotion)
  209. game.scene.add(currentPotion)
  210. }
  211. }
  212. export function addValueToSave(container, key, value) {
  213. let containerString = localStorage.getItem(`${GAME_SAVE_KEY}-${key}`)
  214. if (!containerString) {
  215. container = [value]
  216. } else {
  217. container.push(value)
  218. }
  219. localStorage.setItem(`${GAME_SAVE_KEY}-${key}`, JSON.stringify(container))
  220. }
  221. export function addAmountToSave(key, value) {
  222. let amount = parseInt(localStorage.getItem(`${GAME_SAVE_KEY}-${key}`)) ?? 0
  223. amount += value
  224. localStorage.setItem(`${GAME_SAVE_KEY}-${key}`, amount)
  225. return amount
  226. }
  227. export function removeValueFromSave(container, key, value) {
  228. let containerString = localStorage.getItem(`${GAME_SAVE_KEY}-${key}`)
  229. if (!containerString) {
  230. container = []
  231. } else {
  232. container.remove(value)
  233. }
  234. localStorage.setItem(`${GAME_SAVE_KEY}-${key}`, JSON.stringify(container))
  235. }
  236. export function clearSaveData(stageData) {
  237. localStorage.removeItem(`${GAME_SAVE_KEY}-potion-inventory`)
  238. localStorage.removeItem(`${GAME_SAVE_KEY}-potion-stocked`)
  239. stageData.potionInventory = []
  240. localStorage.setItem(`${GAME_SAVE_KEY}-potion-inventory`, JSON.stringify(stageData.potionInventory))
  241. stageData.potionStocked = []
  242. localStorage.setItem(`${GAME_SAVE_KEY}-potion-stocked`, JSON.stringify(stageData.potionStocked))
  243. stageData.currency = 100
  244. localStorage.setItem(`${GAME_SAVE_KEY}-currency`, stageData.currency)
  245. stageData.currentDay = 1
  246. localStorage.setItem(`${GAME_SAVE_KEY}-currentday`, stageData.currentDay)
  247. stageData.cartItems = []
  248. stageData.ingredientInventory = ["mushroom", "mushroom", "pumpkin", "tomato", "tomato", "lettuce", "lettuce"]
  249. localStorage.setItem(`${GAME_SAVE_KEY}-ingredient-inventory`, JSON.stringify(stageData.ingredientInventory))
  250. updateGameStatusUI(game, stageData)
  251. }
  252. export function loadSaveData(stageData) {
  253. let potionInventoryString = localStorage.getItem(`${GAME_SAVE_KEY}-potion-inventory`)
  254. if (!potionInventoryString) {
  255. localStorage.setItem(`${GAME_SAVE_KEY}-potion-inventory`, JSON.stringify([]))
  256. stageData.potionInventory = []
  257. } else {
  258. stageData.potionInventory = JSON.parse(potionInventoryString)
  259. stageData.potionInventory.sort()
  260. }
  261. let potionsStockedString = localStorage.getItem(`${GAME_SAVE_KEY}-potion-stocked`)
  262. if (!potionsStockedString) {
  263. localStorage.setItem(`${GAME_SAVE_KEY}-potion-stocked`, JSON.stringify([]))
  264. stageData.potionStocked = []
  265. } else {
  266. stageData.potionStocked = JSON.parse(potionsStockedString)
  267. stageData.potionStocked.sort()
  268. }
  269. stageData.currency = localStorage.getItem(`${GAME_SAVE_KEY}-currency`)
  270. if (!stageData.currency) {
  271. localStorage.setItem(`${GAME_SAVE_KEY}-currency`, 100)
  272. stageData.currency = 100
  273. }
  274. stageData.currentDay = localStorage.getItem(`${GAME_SAVE_KEY}-currentday`)
  275. if (!stageData.currentDay) {
  276. localStorage.setItem(`${GAME_SAVE_KEY}-currentday`, 1)
  277. stageData.currentDay = 1
  278. }
  279. let ingredientInventoryString = localStorage.getItem(`${GAME_SAVE_KEY}-ingredient-inventory`)
  280. if (!ingredientInventoryString) {
  281. localStorage.setItem(`${GAME_SAVE_KEY}-ingredient-inventory`, JSON.stringify([]))
  282. stageData.ingredientInventory = ["mushroom", "mushroom", "pumpkin", "tomato", "tomato", "lettuce", "lettuce"]
  283. } else {
  284. stageData.ingredientInventory = JSON.parse(ingredientInventoryString)
  285. stageData.ingredientInventory.sort()
  286. }
  287. }
  288. function buyIngredients(game, stageData) {
  289. let amountToDeduct = 0
  290. stageData.cartItems.forEach(item => {
  291. amountToDeduct += stageData.ingredientInfo[item].cost
  292. addValueToSave(stageData.ingredientInventory, "ingredient-inventory", item)
  293. })
  294. stageData.currency = addAmountToSave("currency", -amountToDeduct)
  295. if(amountToDeduct > 0) {
  296. stageData.soundEffects['audio/cash-register.ogg'].play()
  297. }
  298. updateGameStatusUI(game, stageData)
  299. closeMarketUI(game, stageData)
  300. }
  301. export async function init(inGame) {
  302. game = inGame
  303. loadSaveData(stageData)
  304. stageData.currentRoom = 2
  305. stageData.soundEffects = soundEffects
  306. stageData.selectedIngredients = []
  307. stageData.cartItems = []
  308. stageData.cameraPositions = [
  309. { "camera": new THREE.Vector3(-15, 5, 7), "focus": new THREE.Vector3(-13, 0.1, 0) },
  310. { "camera": new THREE.Vector3(1, 5, 7), "focus": new THREE.Vector3(0, 0.1, 0) },
  311. { "camera": new THREE.Vector3(12, 5, 7), "focus": new THREE.Vector3(18, 0.1, 0) },
  312. { "camera": new THREE.Vector3(1.37, 2.41, 3.77), "focus": new THREE.Vector3(-1.15, 0.79, -0.19) }
  313. ]
  314. const soundFilePaths = [
  315. 'audio/click1.ogg',
  316. 'audio/sinkWater1.ogg',
  317. 'audio/doorOpen_1.ogg',
  318. 'audio/doorClose_4.ogg',
  319. 'audio/drawKnife2.ogg',
  320. 'audio/witch_cackle1.ogg',
  321. 'audio/bubbling.mp3',
  322. 'audio/chest_close_creak.ogg',
  323. 'audio/chest_open_creak.ogg',
  324. 'audio/handleCoins.ogg',
  325. 'audio/impactGlass_medium_000.ogg',
  326. 'audio/impactGlass_medium_001.ogg',
  327. 'audio/impactGlass_medium_002.ogg',
  328. 'audio/impactGlass_medium_003.ogg',
  329. 'audio/impactGlass_medium_004.ogg',
  330. 'audio/impactWood_heavy_002.ogg',
  331. 'audio/impactWood_heavy_004.ogg',
  332. 'audio/impactSoft_medium_002.ogg',
  333. 'audio/impactSoft_medium_004.ogg',
  334. 'audio/cash-register.ogg',
  335. 'audio/store-entrance-bell.ogg'
  336. ]
  337. soundFilePaths.forEach(path => {
  338. soundEffects[path] = new Howl({
  339. src: [path],
  340. preload: true,
  341. })
  342. })
  343. stageData.musicLoop = new Howl({
  344. src: ['audio/Vampires LOOP (All Instruments).ogg'],
  345. preload: true,
  346. loop: true,
  347. volume: 0.5
  348. })
  349. soundEffects['audio/doorClose_4.ogg'].volume(0.5)
  350. soundEffects['audio/doorOpen_1.ogg'].volume(0.5)
  351. soundEffects['audio/bubbling.mp3'].volume(0.5)
  352. soundEffects['audio/store-entrance-bell.ogg'].volume(0.5)
  353. let levelLoader = new LevelLoader(game)
  354. game.camera.position.copy(stageData.cameraPositions[3].camera)
  355. game.lookAtFocus = stageData.cameraPositions[3].focus.clone()
  356. await loadRgbeBackground(game, 'kloppenheim_02_puresky_1k.hdr')
  357. game.scene.background = null
  358. game.scene.fog = new THREE.Fog(0x000000, 12, 20)
  359. let instancedMeshes = await levelLoader.load(levelData.default)
  360. instancedMeshes.forEach(instancedMesh => {
  361. game.scene.add(instancedMesh)
  362. })
  363. stageData.ingredientInfo = ingredientInfo.default
  364. stageData.potionInfo = potionInfo.default
  365. Object.values(stageData.ingredientInfo).forEach(info => {
  366. ingredients.push(new Ingredient(info, game))
  367. })
  368. ///////////////
  369. /// Brewing ///
  370. ///////////////
  371. let shelfSpot = 0
  372. ingredients.forEach(async ingredient => {
  373. await ingredient.spawn(shelfSlots[shelfSpot++])
  374. })
  375. stageData.candycorn = await loadGltf(game, 'models/candycorn.gltf')
  376. stageData.candycorn.position.x = -4.5
  377. stageData.candycorn.position.z = -3.5
  378. game.scene.add(stageData.candycorn)
  379. stageData.pumpkin2 = await loadGltf(game, 'models/pumpkin_orange.gltf')
  380. game.entities.push(stageData.pumpkin2)
  381. stageData.pumpkin2.position.x = -10
  382. stageData.pumpkin2.position.y = 1
  383. stageData.pumpkin2.position.z = 0.5
  384. game.scene.add(stageData.pumpkin2)
  385. jackolantern = await loadGltf(game, 'models/pumpkin_orange_jackolantern.gltf')
  386. game.entities.push(jackolantern)
  387. jackolantern.spin = 0
  388. jackolantern.position.set(3, 0.1, 1)
  389. jackolantern.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -Math.PI / 4)
  390. game.scene.add(jackolantern)
  391. candle = await loadGltf(game, 'models/candle_thin.gltf.glb')
  392. game.entities.push(candle)
  393. candle.position.x = 0
  394. candle.position.y = 1
  395. candle.position.z = -2.5
  396. candle.isLit = false
  397. game.scene.add(candle)
  398. candleLit = await loadGltf(game, 'models/candle_thin_lit.gltf.glb')
  399. game.entities.push(candleLit)
  400. candleLit.position.x = 0
  401. candleLit.position.y = 1
  402. candleLit.position.z = -2.5
  403. candleLit.visible = false
  404. game.scene.add(candleLit)
  405. stageData.cauldronUniforms = THREE.UniformsUtils.merge([
  406. THREE.UniformsLib["common"],
  407. THREE.UniformsLib["lights"]
  408. ])
  409. stageData.cauldronUniforms.uTime = { value: 0 },
  410. stageData.cauldronUniforms.uPixelRatio = { value: Math.min(window.devicePixelRatio, 2) },
  411. stageData.cauldronUniforms.uBlendTime = { value: 0 },
  412. stageData.cauldronUniforms.uPotionColor = { value: new THREE.Vector3(0, 0.8, 0.2) },
  413. stageData.cauldronUniforms.uNextPotionColor = { value: new THREE.Vector3(0, 0.8, 0.2) },
  414. stageData.cauldronUniforms.uTransparency = { value: 0.8 }
  415. stageData.cauldron = await loadGltf(game, 'models/simple_cauldron.gltf.glb')
  416. const cauldronBell = stageData.cauldron.getObjectByName("Sphere015")
  417. cauldronBell.material.side = THREE.DoubleSide
  418. const cauldronTop = stageData.cauldron.getObjectByName("Sphere015_1")
  419. const cauldronTopMaterial = new THREE.ShaderMaterial({
  420. fragmentShader: cauldronFragment,
  421. vertexShader: cauldronVertex,
  422. uniforms: stageData.cauldronUniforms,
  423. transparent: true,
  424. depthWrite: false,
  425. side: THREE.DoubleSide,
  426. lights: true,
  427. })
  428. cauldronTop.material = cauldronTopMaterial
  429. game.entities.push(stageData.cauldron)
  430. stageData.cauldron.position.y = 0.1
  431. game.scene.add(stageData.cauldron)
  432. stageData.brewTutorial1 = buildCanvasText("Click to Brew", { font: "86px Alice" })
  433. stageData.brewTutorial1.position.z = 2.4
  434. stageData.brewTutorial1.position.y = 0.2
  435. stageData.brewTutorial1.rotateOnAxis(new THREE.Vector3(1, 0, 0), -Math.PI / 2)
  436. stageData.brewTutorial1.alreadySeen = false
  437. stageData.brewTutorial1.material.opacity = 0
  438. stageData.brewTutorial1.castShadow = false
  439. game.scene.add(stageData.brewTutorial1)
  440. stageData.brewWitch = await loadGltf(game, 'characters/character_witch.gltf')
  441. game.entities.push(stageData.brewWitch)
  442. stageData.brewWitch.position.x = 1
  443. stageData.brewWitch.position.y = 0.1
  444. stageData.brewWitch.position.z = -1
  445. stageData.brewWitch.stir = false
  446. stageData.brewWitch.bounce = false
  447. stageData.brewWitch.lookAt(stageData.cauldron.position)
  448. game.scene.add(stageData.brewWitch)
  449. stageData.shopWitch = await loadGltf(game, 'characters/character_witch.gltf')
  450. game.entities.push(stageData.shopWitch)
  451. stageData.shopWitch.position.x = -13
  452. stageData.shopWitch.position.y = 0.1
  453. stageData.shopWitch.position.z = -2
  454. game.scene.add(stageData.shopWitch)
  455. stageData.marketWitch = await loadGltf(game, 'characters/character_witch.gltf')
  456. game.entities.push(stageData.marketWitch)
  457. stageData.marketWitch.position.x = 20
  458. stageData.marketWitch.position.y = 0.1
  459. stageData.marketWitch.position.z = 2.5
  460. stageData.marketWitch.rotateOnAxis(THREE.Object3D.DEFAULT_UP, Math.PI)
  461. game.scene.add(stageData.marketWitch)
  462. stageData.spoon = await loadGltf(game, 'models/spoon.gltf')
  463. game.entities.push(stageData.spoon)
  464. stageData.spoon.rotateOnAxis(new THREE.Vector3(1, 0, 0), Math.PI)
  465. stageData.spoon.position.y = 1.25
  466. stageData.spoon.visible = false
  467. game.scene.add(stageData.spoon)
  468. book = await loadGltf(game, 'models/book_grey.gltf.glb')
  469. game.entities.push(book)
  470. book.rotateOnAxis(THREE.Object3D.DEFAULT_UP, Math.PI)
  471. book.position.x = 4.6
  472. book.position.y = 1.9
  473. book.position.z = -3.9
  474. game.scene.add(book)
  475. const bubbleGeometry = new THREE.SphereGeometry(0.1, 24, 24)
  476. const bubbleMaterial = cauldronTopMaterial
  477. //bubbleMaterial.uniforms.uTransparency.value = 0.3
  478. stageData.bubbleParticles = new THREE.InstancedMesh(bubbleGeometry, bubbleMaterial, bubbleCount)
  479. stageData.bubbleParticles.instanceMatrix.setUsage(THREE.DynamicDrawUsage)
  480. stageData.bubbleParticles.visible = false
  481. game.scene.add(stageData.bubbleParticles)
  482. const matrix = new THREE.Matrix4()
  483. for (let index = 0; index < bubbleCount; index++) {
  484. bubblePositions[index] = new THREE.Vector3(0.5 * (Math.random() - 0.5), 0.5, 0.5 * (Math.random() - 0.5))
  485. bubbleLifespan[index] = 7 - (index * 0.5)
  486. bubbleScale[index] = 0.2
  487. bubbleVelocity[index] = new THREE.Vector3(0, 0.01, 0)
  488. }
  489. const quaternion = new THREE.Quaternion()
  490. const scaleVector = new THREE.Vector3(1, 1, 1)
  491. for (let index = 0; index < bubbleCount; index++) {
  492. quaternion.setFromAxisAngle(THREE.Object3D.DEFAULT_UP, 0)
  493. const scale = scaleVector.set(bubbleScale[index], bubbleScale[index], bubbleScale[index])
  494. matrix.compose(bubblePositions[index], quaternion, scale)
  495. stageData.bubbleParticles.setMatrixAt(index, matrix)
  496. }
  497. doorway = await loadGltf(game, 'models/wall_doorway.glb')
  498. doorway.position.set(-6, 0, -2)
  499. doorway.castShadow = false
  500. doorway.traverse((child) => {
  501. if (child.isMesh) {
  502. child.castShadow = false
  503. }
  504. })
  505. doorway.rotateOnAxis(THREE.Object3D.DEFAULT_UP, Math.PI / 2)
  506. doorway.isOpen = false
  507. doorway.isMoving = false
  508. game.entities.push(doorway)
  509. game.scene.add(doorway)
  510. doorway2 = await loadGltf(game, 'models/wall_doorway.glb')
  511. doorway2.position.set(6, 0, 2)
  512. doorway2.castShadow = false
  513. doorway2.traverse((child) => {
  514. if (child.isMesh) {
  515. child.castShadow = false
  516. }
  517. })
  518. doorway2.rotateOnAxis(THREE.Object3D.DEFAULT_UP, Math.PI / 2)
  519. doorway2.isOpen = false
  520. doorway2.isMoving = false
  521. game.entities.push(doorway2)
  522. game.scene.add(doorway2)
  523. ////////////
  524. /// Shop ///
  525. ////////////
  526. // const debugSphereGeometry = new THREE.SphereGeometry(0.1)
  527. // const debugMaterial = new THREE.MeshBasicMaterial({color: "magenta"})
  528. // const debugSphere = new THREE.Mesh(debugSphereGeometry, debugMaterial)
  529. // customerSlots.forEach(slot => {
  530. // debugSphere.position.copy(slot.position)
  531. // game.scene.add(debugSphere.clone())
  532. // })
  533. stageData.displayedPotions = []
  534. updatePotionShelfDisplay()
  535. lollipop = await loadGltf(game, 'models/lollipop_green.gltf')
  536. lollipop.position.x = -11.5
  537. lollipop.position.y = 1.28
  538. lollipop.position.z = -3.4
  539. lollipop.rotateOnAxis(new THREE.Vector3(1, 0, 0), Math.PI / 2)
  540. lollipop.rotateOnAxis(new THREE.Vector3(0, 0, 1), Math.PI / 2 + -0.3)
  541. game.entities.push(lollipop)
  542. game.scene.add(lollipop)
  543. stageData.chest = await loadGltf(game, 'models/chest_large.glb')
  544. stageData.chest.scale.set(0.5, 0.5, 0.5)
  545. stageData.chest.position.x = -15.5
  546. stageData.chest.position.y = 1
  547. stageData.chest.position.z = 0
  548. stageData.chest.rotateOnAxis(THREE.Object3D.DEFAULT_UP, Math.PI / 4)
  549. game.entities.push(stageData.chest)
  550. game.scene.add(stageData.chest)
  551. stageData.shopTutorial1 = buildCanvasText("Click to Sell", { font: "100px Alice" })
  552. stageData.shopTutorial1.position.x = -15.5
  553. stageData.shopTutorial1.position.z = 0.2
  554. stageData.shopTutorial1.position.y = 1.8
  555. stageData.shopTutorial1.alreadySeen = false
  556. stageData.shopTutorial1.scale.set(0.6, 0.6, 0.6)
  557. stageData.shopTutorial1.material.opacity = 0
  558. stageData.shopTutorial1.castShadow = false
  559. game.scene.add(stageData.shopTutorial1)
  560. stageData.shopTutorial2 = buildCanvasText("Pick the correct potion", { font: "72px Alice" })
  561. stageData.shopTutorial2.position.x = -10
  562. stageData.shopTutorial2.position.z = -3.4
  563. stageData.shopTutorial2.position.y = 1.5
  564. stageData.shopTutorial2.alreadySeen = false
  565. stageData.shopTutorial2.scale.set(1, 1, 1)
  566. stageData.shopTutorial2.material.opacity = 0
  567. stageData.shopTutorial2.castShadow = false
  568. game.scene.add(stageData.shopTutorial2)
  569. stageData.coin = await loadGltf(game, 'models/coin.gltf.glb')
  570. stageData.coin.position.x = -12
  571. stageData.coin.position.y = 1.1
  572. stageData.coin.position.z = 0
  573. game.entities.push(stageData.coin)
  574. game.scene.add(stageData.coin)
  575. stageData.customers = []
  576. //////////////
  577. /// Market ///
  578. //////////////
  579. stageData.sellingSkeleton = await loadGltf(game, 'characters/character_skeleton_mage.gltf')
  580. stageData.sellingSkeleton.position.x = 20
  581. stageData.sellingSkeleton.position.y = 0.1
  582. stageData.sellingSkeleton.position.z = -1
  583. stageData.sellingSkeleton.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -Math.PI / 4)
  584. game.entities.push(stageData.sellingSkeleton)
  585. game.scene.add(stageData.sellingSkeleton)
  586. stageData.sign = await loadGltf(game, 'models/sign_left.gltf')
  587. stageData.sign.position.x = 14
  588. stageData.sign.position.y = 0.1
  589. stageData.sign.position.z = 2
  590. game.entities.push(stageData.sign)
  591. game.scene.add(stageData.sign)
  592. stageData.mushroomCrate = await loadGltf(game, 'models/crate_mushrooms.gltf')
  593. stageData.mushroomCrate.scale.set(0.5, 0.5, 0.5)
  594. stageData.mushroomCrate.position.x = 19.5
  595. stageData.mushroomCrate.position.z = 0.5
  596. stageData.mushroomCrate.rotateOnAxis(THREE.Object3D.DEFAULT_UP, Math.PI / 4)
  597. game.entities.push(stageData.mushroomCrate)
  598. game.scene.add(stageData.mushroomCrate)
  599. stageData.tomatoCrate = await loadGltf(game, 'models/crate_tomatoes.gltf')
  600. stageData.tomatoCrate.scale.set(0.5, 0.5, 0.5)
  601. stageData.tomatoCrate.position.x = 21
  602. game.entities.push(stageData.tomatoCrate)
  603. game.scene.add(stageData.tomatoCrate)
  604. stageData.lettuceCrate = await loadGltf(game, 'models/crate_lettuce.gltf')
  605. stageData.lettuceCrate.scale.set(0.5, 0.5, 0.5)
  606. stageData.lettuceCrate.position.x = 18.5
  607. stageData.lettuceCrate.position.z = -0.5
  608. game.entities.push(stageData.lettuceCrate)
  609. game.scene.add(stageData.lettuceCrate)
  610. const coffin = await loadGltf(game, 'models/coffin_decorated.gltf')
  611. coffin.position.x = 23
  612. coffin.position.z = 6
  613. coffin.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -Math.PI / 4)
  614. game.scene.add(coffin)
  615. const candy = await loadGltf(game, 'models/candy_orange_A.gltf')
  616. candy.position.x = 21
  617. candy.position.y = 0.25
  618. candy.position.z = 6
  619. candy.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -Math.PI / 4)
  620. game.scene.add(candy)
  621. const candyBucket = await loadGltf(game, 'models/candy_bucket_B_decorated.gltf')
  622. candyBucket.position.x = 21.5
  623. candyBucket.position.y = 0.1
  624. candyBucket.position.z = 5.5
  625. candyBucket.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -Math.PI / 2)
  626. game.scene.add(candyBucket)
  627. /**
  628. * Fireflies
  629. */
  630. stageData.firefliesUniforms = {
  631. uTime: { value: 0 },
  632. uPixelRatio: { value: Math.min(window.devicePixelRatio, 2) }
  633. }
  634. const firefliesMaterial = new THREE.ShaderMaterial({
  635. fragmentShader: firefliesFragment,
  636. vertexShader: firefliesVertex,
  637. uniforms: stageData.firefliesUniforms,
  638. transparent: true,
  639. depthWrite: false,
  640. blending: THREE.AdditiveBlending
  641. })
  642. const firefliesGeometry = new THREE.BufferGeometry()
  643. const firefliesCount = 50
  644. const positionArray = new Float32Array(firefliesCount * 3)
  645. const scaleArray = new Float32Array(firefliesCount)
  646. for (let i = 0; i < firefliesCount; i++) {
  647. positionArray[i * 3 + 0] = 24 * (Math.random() - 0.5) + 18
  648. positionArray[i * 3 + 1] = 4 * Math.random() + 2
  649. positionArray[i * 3 + 2] = 16 * (Math.random() - 0.5)
  650. scaleArray[i] = 0.8 * Math.random() + 1.2
  651. }
  652. firefliesGeometry.setAttribute('position', new THREE.BufferAttribute(positionArray, 3))
  653. firefliesGeometry.setAttribute('aScale', new THREE.BufferAttribute(scaleArray, 1))
  654. const fireflies = new THREE.Points(firefliesGeometry, firefliesMaterial)
  655. game.scene.add(fireflies)
  656. ////////////////
  657. /// Lighting ///
  658. ////////////////
  659. const ambientLight = new THREE.AmbientLight(0xFFFFFF, 1)
  660. game.scene.add(ambientLight)
  661. const shadowSize = 24
  662. directionalLight = new THREE.DirectionalLight(0xFFFFFF, 0.9)
  663. directionalLight.position.set(8, 10, 6)
  664. directionalLight.castShadow = true
  665. directionalLight.shadow.camera.left = -shadowSize
  666. directionalLight.shadow.camera.right = shadowSize
  667. directionalLight.shadow.camera.top = -shadowSize
  668. directionalLight.shadow.camera.bottom = shadowSize
  669. directionalLight.shadow.camera.far = 28
  670. directionalLight.shadow.mapSize.width = Math.min(game.renderer.capabilities.maxTextureSize, 2048)
  671. directionalLight.shadow.mapSize.height = Math.min(game.renderer.capabilities.maxTextureSize, 2048)
  672. directionalLight.shadow.bias = -0.005
  673. directionalLight.shadow.radius = 6
  674. directionalLight.cameraOffset = new THREE.Vector3()
  675. directionalLight.cameraOffset.copy(directionalLight.position)
  676. directionalLight.cameraOffset.sub(new THREE.Vector3(0, 0, 0))
  677. directionalLight.target = game.camera
  678. directionalLight.update = function () {
  679. const currentOffset = new THREE.Vector3()
  680. currentOffset.copy(directionalLight.cameraOffset).add(game.camera.position)
  681. directionalLight.position.set(currentOffset.x, currentOffset.y, currentOffset.z)
  682. if (directionalLight.shadow) {
  683. directionalLight.shadow.camera.position.set(currentOffset.x, currentOffset.y, currentOffset.z)
  684. }
  685. }
  686. game.scene.add(directionalLight)
  687. // const shadowHelper = new THREE.CameraHelper( directionalLight.shadow.camera )
  688. // game.scene.add(shadowHelper)
  689. mainMenuUI(game, stageData)
  690. optionsUI(game, stageData)
  691. creditsUI(game, stageData)
  692. navigationUI(game, stageData)
  693. brewUI(game, stageData)
  694. shopUI(game, stageData)
  695. marketUI(game, stageData)
  696. gameOverUI(game, stageData)
  697. updateGameStatusUI(game, stageData)
  698. stageData.beginBrew = () => { beginBrew(game, stageData) }
  699. stageData.beginSell = () => { beginSell(game, stageData) }
  700. stageData.buyIngredients = () => { buyIngredients(game, stageData)}
  701. stageData.adjustMasterVolume = (volume) => {
  702. Howler.volume(volume / 100)
  703. }
  704. stageData.adjustMusicVolume = (volume) => {
  705. stageData.musicLoop.volume(volume / 100)
  706. }
  707. ///////////
  708. // DEBUG //
  709. ///////////
  710. // moveToRoom(ROOM_SHOP)
  711. // closeMainMenuUI(game, stageData)
  712. // const planeGeometry = new THREE.PlaneGeometry(1,1)
  713. // const debugPlane = new THREE.Mesh(planeGeometry, textBubbleMaterial)
  714. // debugPlane.position.x = 2
  715. // debugPlane.position.y = 1
  716. // debugPlane.scale.set(2,2,2)
  717. // game.scene.add(debugPlane)
  718. }
  719. export function update(game) {
  720. let elapsedTime = game.clock.getElapsedTime()
  721. ingredients.forEach(ingredient => {
  722. ingredient.wobble()
  723. })
  724. stageData.candycorn.position.y = 0.125 * Math.sin(4.1 * elapsedTime) + 3.0
  725. stageData.candycorn.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -0.02)
  726. directionalLight.update()
  727. raycast.setFromCamera(game.mousePosition, game.camera)
  728. Howler.pos(game.camera.position.x, game.camera.position.y, game.camera.position.z)
  729. Howler.orientation(game.camera.position.x, game.camera.position.y, game.camera.position.z, 0, 1, 0)
  730. const quaternion = new THREE.Quaternion()
  731. const scaleVector = new THREE.Vector3(1, 1, 1)
  732. const matrix = new THREE.Matrix4()
  733. for (let index = 0; index < bubbleCount; index++) {
  734. bubblePositions[index].add(bubbleVelocity[index])
  735. bubbleScale[index] = Math.min(bubbleScale[index] + 0.01, 1)
  736. bubbleLifespan[index] -= 0.1
  737. if (bubbleLifespan[index] <= 0) {
  738. bubbleLifespan[index] = 7
  739. bubblePositions[index].set(0.5 * (Math.random() - 0.5), 0.5, 0.5 * (Math.random() - 0.5))
  740. bubbleScale[index] = 0.2
  741. }
  742. //quaternion.setFromAxisAngle(THREE.Object3D.DEFAULT_UP, 0)
  743. const scale = scaleVector.set(bubbleScale[index], bubbleScale[index], bubbleScale[index])
  744. matrix.compose(bubblePositions[index], quaternion, scale)
  745. stageData.bubbleParticles.setMatrixAt(index, matrix)
  746. }
  747. stageData.bubbleParticles.instanceMatrix.needsUpdate = true
  748. if (stageData.brewWitch.stir) {
  749. stageData.spoon.position.x = 0.125 * Math.sin(4 * elapsedTime)
  750. stageData.spoon.position.z = 0.125 * Math.cos(4 * elapsedTime)
  751. }
  752. if (stageData.brewWitch.bounce) {
  753. stageData.brewWitch.scale.x = 1 + (0.03125 * Math.sin(12 * elapsedTime))
  754. stageData.brewWitch.scale.y = 1 + (-0.03125 * Math.sin(12 * elapsedTime))
  755. stageData.brewWitch.scale.z = 1 + (0.03125 * Math.sin(12 * elapsedTime))
  756. } else {
  757. stageData.brewWitch.scale.x = 1
  758. stageData.brewWitch.scale.y = 1
  759. stageData.brewWitch.scale.z = 1
  760. }
  761. if (jackolantern.spin > 0) {
  762. jackolantern.spin -= 0.05
  763. jackolantern.rotateOnAxis(THREE.Object3D.DEFAULT_UP, -0.1)
  764. if (jackolantern.spin < 0) {
  765. jackolantern.spin = 0
  766. }
  767. }
  768. stageData.sellingSkeleton.scale.x = 1 + (0.03125 * Math.sin(12 * elapsedTime))
  769. stageData.sellingSkeleton.scale.y = 1 + (-0.03125 * Math.sin(12 * elapsedTime))
  770. stageData.sellingSkeleton.scale.z = 1 + (0.03125 * Math.sin(12 * elapsedTime))
  771. stageData.firefliesUniforms.uTime.value = elapsedTime
  772. stageData.cauldronUniforms.uTime.value = elapsedTime
  773. stageData.customers.forEach(customer => {
  774. customer.update(elapsedTime)
  775. })
  776. candle.position.y = 0.625 * Math.sin(0.5 * elapsedTime) + 1.3
  777. candleLit.position.y = 0.625 * Math.sin(0.5 * elapsedTime) + 1.3
  778. let intersects = raycast.intersectObjects(game.entities.filter(entity => entity.visible))
  779. if (intersects.length > 0) {
  780. document.body.style.cursor = "pointer"
  781. } else {
  782. document.body.style.cursor = "default"
  783. }
  784. }
  785. function isAChildOf(parent, childToCheck) {
  786. if (parent == childToCheck) return true
  787. if (childToCheck.parent != null) {
  788. return isAChildOf(parent, childToCheck.parent)
  789. }
  790. return false
  791. }
  792. export function onClick() {
  793. //drawDebugLine(game, witch.position, getForwardVector(witch).multiplyScalar(10), 0xff0000, 1000)
  794. //drawDebugLine(game, witch.position, getRightVector(witch).multiplyScalar(10), 0x00ff00, 1000)
  795. let intersects = raycast.intersectObjects(game.entities.filter(entity => entity.visible))
  796. if (intersects.length > 0) {
  797. intersects.every(intersect => {
  798. switch (stageData.currentRoom) {
  799. case ROOM_SHOP:
  800. //SHOP CLICK ACTIONS HERE
  801. if (isAChildOf(stageData.chest, intersect.object)) {
  802. if (stageData.isSellingPotions) {
  803. return false
  804. }
  805. if (stageData.shopInactivityHandle) {
  806. clearTimeout(stageData.shopInactivityHandle)
  807. stageData.shopInactivityHandle = 0
  808. }
  809. if (stageData.chest.isStocking) {
  810. closeShopUI(game, stageData)
  811. } else {
  812. openShopUI(game, stageData)
  813. if (stageData.shopTutorial1.material.opacity > 0) {
  814. gsap.to(stageData.shopTutorial1.material, {
  815. duration: 1.5, opacity: 0, onComplete: () => {
  816. stageData.shopTutorial1.castShadow = false
  817. stageData.shopTutorial1.alreadySeen = true
  818. }
  819. })
  820. }
  821. }
  822. return false
  823. }
  824. if (isAChildOf(stageData.shopWitch, intersect.object)) {
  825. if (stageData.isSellingPotions) {
  826. return false
  827. }
  828. if (stageData.shopInactivityHandle) {
  829. clearTimeout(stageData.shopInactivityHandle)
  830. stageData.shopInactivityHandle = 0
  831. }
  832. if (stageData.chest.isStocking) {
  833. closeShopUI(game, stageData)
  834. } else {
  835. openShopUI(game, stageData)
  836. if (stageData.shopTutorial1.material.opacity > 0) {
  837. gsap.to(stageData.shopTutorial1.material, {
  838. duration: 1.5, opacity: 0, onComplete: () => {
  839. stageData.shopTutorial1.castShadow = false
  840. stageData.shopTutorial1.alreadySeen = true
  841. }
  842. })
  843. }
  844. }
  845. return false
  846. }
  847. if (isAChildOf(stageData.coin, intersect.object)) {
  848. let coinMotionPath = [{ x: -12, y: 1.1, z: 1 }, { x: -12, y: 2, z: 2 }, { x: -15.5, y: 2, z: 2 }, { x: -15.5, y: 1.2, z: 0 }]
  849. gsap.to(stageData.coin.position, {
  850. duration: 3.5, motionPath: coinMotionPath, onComplete: () => {
  851. stageData.soundEffects['audio/handleCoins.ogg'].play()
  852. closeChest(stageData.chest, () => {
  853. stageData.coin.scale.set(0, 0, 0)
  854. stageData.coin.position.set(-12, 1.1, 0)
  855. gsap.to(stageData.coin.scale, {
  856. ease: "elastic",
  857. duration: 0.7, x: 1, y: 1, z: 1,
  858. })
  859. })
  860. }
  861. })
  862. setTimeout(() => {
  863. openChest(stageData.chest)
  864. }, 700)
  865. return false
  866. }
  867. stageData.displayedPotions.forEach((potion) => {
  868. if (isAChildOf(potion, intersect.object)) {
  869. if (stageData.isSellingPotions) {
  870. if (stageData.sellInactivityHandle) {
  871. clearTimeout(stageData.sellInactivityHandle)
  872. stageData.sellInactivityHandle = 0
  873. }
  874. if (stageData.customers[0].isMatchingPotion(potion.potionData)) {
  875. if (stageData.shopTutorial2.material.opacity > 0) {
  876. gsap.to(stageData.shopTutorial2.material, {
  877. duration: 1.5, opacity: 0, onComplete: () => {
  878. stageData.shopTutorial2.castShadow = false
  879. stageData.shopTutorial2.alreadySeen = true
  880. }
  881. })
  882. }
  883. const firstCustomer = stageData.customers[0]
  884. firstCustomer.hideDesire()
  885. const potionMotionPath = [{ x: -11.5, y: 2.75, z: -3.25 }, { x: -12, y: 2, z: -2 }, { x: -13, y: 0.75, z: 2.5 }]
  886. gsap.to(potion.position, {
  887. duration: 2, motionPath: potionMotionPath, onComplete: () => {
  888. removeValueFromSave(stageData.potionStocked, 'potion-stocked', potion.potionData.name)
  889. updatePotionShelfDisplay()
  890. firstCustomer.acceptPotion()
  891. stageData.soundEffects['audio/cash-register.ogg'].play()
  892. stageData.currency = addAmountToSave("currency", potion.potionData.value)
  893. updateGameStatusUI(game, stageData)
  894. //move money from customer to chest
  895. //add money to save data
  896. //move customer out of room
  897. nextCustomer()
  898. //display next customer desire
  899. //if no more customers or no more valid potions, end selling
  900. }
  901. })
  902. } else {
  903. //TODO: potion does not match
  904. playBottleClink()
  905. gsap.fromTo(potion.rotation, { duration: 0.1, z: 0.2 }, { duration: 0.1, z: 0 })
  906. stageData.customers[0].rejectPotion()
  907. if (stageData.customers[0].rejectCount >= 3) {
  908. stageData.customers[0].showSad()
  909. nextCustomer()
  910. }
  911. }
  912. } else {
  913. playBottleClink()
  914. gsap.fromTo(potion.rotation, { duration: 0.1, z: 0.2 }, { duration: 0.1, z: 0 })
  915. }
  916. }
  917. })
  918. if (isAChildOf(stageData.pumpkin2, intersect.object)) {
  919. if (stageData.pumpkin2.isMoving) {
  920. return
  921. }
  922. stageData.pumpkin2.isMoving = true
  923. gsap.to(stageData.pumpkin2.position, {
  924. duration: 2, y: 3, onComplete: () => {
  925. setTimeout(() => {
  926. stageData.soundEffects['audio/impactWood_heavy_002.ogg'].play()
  927. }, 400)
  928. setTimeout(() => {
  929. stageData.soundEffects['audio/impactSoft_medium_002.ogg'].play()
  930. }, 800)
  931. gsap.to(stageData.pumpkin2.position, {
  932. duration: 1, y: 1, ease: "bounce", onComplete: () => {
  933. stageData.pumpkin2.isMoving = false
  934. }
  935. })
  936. }
  937. })
  938. return false
  939. }
  940. break;
  941. case ROOM_BREW:
  942. //BREW CLICK ACTIONS HERE
  943. if (isAChildOf(jackolantern, intersect.object)) {
  944. soundEffects['audio/drawKnife2.ogg'].play()
  945. jackolantern.spin += Math.PI
  946. return false
  947. }
  948. if (isAChildOf(book, intersect.object)) {
  949. //soundEffects['audio/drawKnife2.ogg'].play()
  950. //jackolantern.spin += Math.PI
  951. let bookMotionPath = [{ x: 4.6, y: 1.9, z: 0 }, { x: 4.6, y: 1.9, z: -3.9 }]
  952. gsap.to(book.position, {
  953. duration: 6, motionPath: bookMotionPath, onComplete: () => {
  954. }
  955. })
  956. return false
  957. }
  958. if (isAChildOf(stageData.brewWitch, intersect.object)) {
  959. if (stageData.cauldron.isBrewing) {
  960. return false
  961. }
  962. if (stageData.brewInactivityHandle) {
  963. clearTimeout(stageData.brewInactivityHandle)
  964. stageData.brewInactivityHandle = 0
  965. }
  966. if (stageData.cauldron.brewMenuOpen) {
  967. closeBrewUI(game, stageData)
  968. } else {
  969. openBrewUI(game, stageData)
  970. //cauldron.isBrewing = true
  971. if (stageData.brewTutorial1.material.opacity > 0) {
  972. gsap.to(stageData.brewTutorial1.material, {
  973. duration: 1.5, opacity: 0, onComplete: () => {
  974. stageData.brewTutorial1.castShadow = false
  975. stageData.brewTutorial1.alreadySeen = true
  976. }
  977. })
  978. }
  979. }
  980. return false
  981. }
  982. if (isAChildOf(stageData.cauldron, intersect.object)) {
  983. if (stageData.cauldron.isBrewing) {
  984. return false
  985. }
  986. if (stageData.brewInactivityHandle) {
  987. clearTimeout(stageData.brewInactivityHandle)
  988. stageData.brewInactivityHandle = 0
  989. }
  990. if (stageData.cauldron.brewMenuOpen) {
  991. closeBrewUI(game, stageData)
  992. } else {
  993. openBrewUI(game, stageData)
  994. if (stageData.brewTutorial1.material.opacity > 0) {
  995. gsap.to(stageData.brewTutorial1.material, {
  996. duration: 1.5, opacity: 0, onComplete: () => {
  997. stageData.brewTutorial1.castShadow = false
  998. stageData.brewTutorial1.alreadySeen = true
  999. }
  1000. })
  1001. }
  1002. //cauldron.isBrewing = true
  1003. }
  1004. // let soundId = soundEffects['audio/sinkWater1.ogg'].play()
  1005. // soundEffects['audio/sinkWater1.ogg'].once('play', () => {
  1006. // soundEffects['audio/sinkWater1.ogg'].volume(0.5, soundId)
  1007. // // soundEffects['audio/sinkWater1.ogg'].pos(cauldron.position.x, cauldron.position.y, cauldron.position.z, soundId)
  1008. // // soundEffects['audio/sinkWater1.ogg'].pannerAttr({
  1009. // // panningModel: 'HRTF',
  1010. // // refDistance: 1.0,
  1011. // // rolloffFactor: 0.8,
  1012. // // distanceModel: 'exponential',
  1013. // // }, soundId)
  1014. // soundEffects['audio/sinkWater1.ogg'].stereo(1, soundId)
  1015. // //console.log(soundEffects['audio/sinkWater1.ogg'])
  1016. // }, soundId)
  1017. return false
  1018. }
  1019. if (isAChildOf(candle, intersect.object)) {
  1020. candle.isLit = true
  1021. candleLit.visible = true
  1022. candle.visible = false
  1023. return false
  1024. }
  1025. if (isAChildOf(candleLit, intersect.object)) {
  1026. candle.isLit = false
  1027. candleLit.visible = false
  1028. candle.visible = true
  1029. return false
  1030. }
  1031. break;
  1032. case ROOM_MARKET:
  1033. //MARKET CLICK ACTIONS HERE
  1034. if (isAChildOf(stageData.sign, intersect.object)) {
  1035. previousRoom(game, stageData)
  1036. return false
  1037. }
  1038. if(isAChildOf(stageData.mushroomCrate, intersect.object) ||
  1039. isAChildOf(stageData.lettuceCrate, intersect.object) ||
  1040. isAChildOf(stageData.tomatoCrate, intersect.object) ||
  1041. isAChildOf(stageData.sellingSkeleton, intersect.object) ||
  1042. isAChildOf(stageData.marketWitch, intersect.object)
  1043. ) {
  1044. if (stageData.sellingSkeleton.marketMenuOpen) {
  1045. closeMarketUI(game, stageData)
  1046. } else {
  1047. openMarketUI(game, stageData)
  1048. }
  1049. return false
  1050. }
  1051. break;
  1052. }
  1053. if (isAChildOf(doorway, intersect.object)) {
  1054. if (stageData.currentRoom == ROOM_BREW) {
  1055. previousRoom(game, stageData)
  1056. } else if (stageData.currentRoom == ROOM_SHOP) {
  1057. nextRoom(game, stageData)
  1058. }
  1059. return false
  1060. }
  1061. if (isAChildOf(doorway2, intersect.object)) {
  1062. if (stageData.currentRoom == ROOM_BREW) {
  1063. nextRoom(game, stageData)
  1064. } else if (stageData.currentRoom == ROOM_MARKET) {
  1065. previousRoom(game, stageData)
  1066. }
  1067. return false
  1068. }
  1069. })
  1070. }
  1071. }
  1072. function nextCustomer() {
  1073. const firstCustomer = stageData.customers.shift()
  1074. if (!firstCustomer) {
  1075. return
  1076. }
  1077. const customerMotionPath = [{ x: -11, y: 0.1, z: 3 }, { x: -8, y: 0.1, z: 3 }, { x: -4, y: 0.1, z: 10 }]
  1078. setTimeout(() => {
  1079. stageData.soundEffects['audio/store-entrance-bell.ogg'].play()
  1080. }, 3000)
  1081. gsap.to(firstCustomer.object3d.position, {
  1082. duration: 8, motionPath: customerMotionPath, onComplete: () => {
  1083. game.scene.remove(firstCustomer.object3d)
  1084. }
  1085. })
  1086. gsap.to(firstCustomer.object3d.rotation, {
  1087. duration: 1, y: Math.PI, onComplete: () => {
  1088. }, onUpdate: () => {
  1089. firstCustomer.requestBillboard.lookAt(game.camera.position)
  1090. }
  1091. })
  1092. //const shopperPosition = customerSlots[stageData.customers.length].position
  1093. //move other customers forward
  1094. for (let i = 0; i < stageData.customers.length; i++) {
  1095. const customer = stageData.customers[i]
  1096. const shopperPosition = customerSlots[i].position
  1097. gsap.to(customer.object3d.position, { duration: 1.5, x: shopperPosition.x, y: shopperPosition.y, z: shopperPosition.z })
  1098. }
  1099. if (stageData.customers.length == 0) {
  1100. stageData.isSellingPotions = false
  1101. stageData.currentDay = addAmountToSave("currentday", 1)
  1102. updateGameStatusUI(game, stageData)
  1103. if(stageData.currency >= 1000) {
  1104. showGameOverUI(game, stageData)
  1105. }
  1106. } else {
  1107. stageData.customers[0].showDesire()
  1108. if (stageData.potionStocked.length < 1) {
  1109. stageData.customers[0].rejectPotion(3)
  1110. stageData.customers[0].showSad()
  1111. nextCustomer()
  1112. }
  1113. }
  1114. }
  1115. export function playBottleClink() {
  1116. setTimeout(() => {
  1117. let randomSound2 = Math.floor(5 * Math.random())
  1118. stageData.soundEffects[`audio/impactGlass_medium_00${randomSound2}.ogg`].play()
  1119. }, 50)
  1120. let randomSound = Math.floor(5 * Math.random())
  1121. stageData.soundEffects[`audio/impactGlass_medium_00${randomSound}.ogg`].play()
  1122. }
  1123. function openChest(chest) {
  1124. let lid = chest.getObjectByName("chest_large_lid")
  1125. if (chest.isOpen) {
  1126. return
  1127. }
  1128. if (!chest.isMoving) {
  1129. soundEffects['audio/chest_open_creak.ogg'].play()
  1130. chest.isMoving = true
  1131. gsap.to(lid.rotation, {
  1132. duration: 2.5, x: -(Math.PI / 2) + (Math.PI / 8), ease: "elastic", onComplete: () => {
  1133. chest.isOpen = true
  1134. chest.isMoving = false
  1135. }
  1136. })
  1137. }
  1138. }
  1139. function closeChest(chest, onComplete = () => { }) {
  1140. let lid = chest.getObjectByName("chest_large_lid")
  1141. if (!chest.isOpen) {
  1142. return
  1143. }
  1144. if (!chest.isMoving) {
  1145. soundEffects['audio/chest_close_creak.ogg'].play()
  1146. chest.isMoving = true
  1147. gsap.to(lid.rotation, {
  1148. duration: 1.5, x: 0, ease: "bounce", onComplete: () => {
  1149. chest.isOpen = false
  1150. chest.isMoving = false
  1151. onComplete()
  1152. }
  1153. })
  1154. }
  1155. }
  1156. function openDoorway(doorway) {
  1157. let door = doorway.getObjectByName("wall_doorway_door")
  1158. if (doorway.isOpen) {
  1159. return
  1160. }
  1161. if (!doorway.isMoving) {
  1162. soundEffects['audio/doorOpen_1.ogg'].play()
  1163. doorway.isMoving = true
  1164. gsap.to(door.rotation, {
  1165. duration: 2.5, y: -Math.PI / 2, ease: "elastic", onComplete: () => {
  1166. doorway.isOpen = true
  1167. doorway.isMoving = false
  1168. }
  1169. })
  1170. }
  1171. }
  1172. function closeDoorway(doorway) {
  1173. let door = doorway.getObjectByName("wall_doorway_door")
  1174. if (!doorway.isOpen) {
  1175. return
  1176. }
  1177. if (!doorway.isMoving) {
  1178. soundEffects['audio/doorClose_4.ogg'].play()
  1179. doorway.isMoving = true
  1180. gsap.to(door.rotation, {
  1181. duration: 2.5, y: 0, ease: "elastic", onComplete: () => {
  1182. doorway.isOpen = false
  1183. doorway.isMoving = false
  1184. }
  1185. })
  1186. }
  1187. }
  1188. function moveToShop() {
  1189. closeBrewUI(game, stageData)
  1190. openDoorway(doorway)
  1191. const camPosition = stageData.cameraPositions[0]
  1192. gsap.to(game.camera.position, {
  1193. duration: 2.5, x: camPosition.camera.x, y: camPosition.camera.y, z: camPosition.camera.z, onComplete: () => {
  1194. closeDoorway(doorway)
  1195. }
  1196. })
  1197. gsap.to(game.lookAtFocus, { duration: 2.5, x: camPosition.focus.x, y: camPosition.focus.y, z: camPosition.focus.z })
  1198. stageData.currentRoom = ROOM_SHOP
  1199. shopTutorialPrompt(stageData)
  1200. }
  1201. function moveToBrew() {
  1202. let doorwayToOpen = doorway
  1203. if (stageData.currentRoom == ROOM_MARKET) {
  1204. doorwayToOpen = doorway2
  1205. }
  1206. openDoorway(doorwayToOpen)
  1207. const camPosition = stageData.cameraPositions[1]
  1208. gsap.to(game.camera.position, {
  1209. duration: 2.5, x: camPosition.camera.x, y: camPosition.camera.y, z: camPosition.camera.z, onComplete: () => {
  1210. closeDoorway(doorwayToOpen)
  1211. }
  1212. })
  1213. gsap.to(game.lookAtFocus, { duration: 2.5, x: camPosition.focus.x, y: camPosition.focus.y, z: camPosition.focus.z })
  1214. stageData.currentRoom = ROOM_BREW
  1215. brewTutorialPrompt(stageData)
  1216. }
  1217. function moveToMarket() {
  1218. closeBrewUI(game, stageData)
  1219. openDoorway(doorway2)
  1220. const camPosition = stageData.cameraPositions[2]
  1221. gsap.to(game.camera.position, {
  1222. duration: 2.5, x: camPosition.camera.x, y: camPosition.camera.y, z: camPosition.camera.z, onComplete: () => {
  1223. closeDoorway(doorway2)
  1224. }
  1225. })
  1226. gsap.to(game.lookAtFocus, { duration: 2.5, x: camPosition.focus.x, y: camPosition.focus.y, z: camPosition.focus.z })
  1227. stageData.currentRoom = ROOM_MARKET
  1228. }
  1229. export function moveToRoom(roomId) {
  1230. if (roomId == stageData.currentRoom) {
  1231. return
  1232. }
  1233. switch (roomId) {
  1234. case ROOM_SHOP:
  1235. moveToShop()
  1236. break;
  1237. case ROOM_BREW:
  1238. moveToBrew()
  1239. break;
  1240. case ROOM_MARKET:
  1241. moveToMarket()
  1242. break;
  1243. }
  1244. }
  1245. let keyHistory = []
  1246. export function onKeyPress(code) {
  1247. if (game.keyboard['Digit1'] && stageData.currentRoom == ROOM_BREW) {
  1248. moveToRoom(ROOM_SHOP)
  1249. keyHistory = []
  1250. }
  1251. if (game.keyboard['Digit2'] && stageData.currentRoom != ROOM_BREW) {
  1252. moveToRoom(ROOM_BREW)
  1253. keyHistory = []
  1254. }
  1255. if (game.keyboard['Digit3'] && stageData.currentRoom == ROOM_BREW) {
  1256. moveToRoom(ROOM_MARKET)
  1257. keyHistory = []
  1258. }
  1259. if (game.keyboard['Digit9'] || game.keyboard['F9']) {
  1260. game.orbitControls.enabled = !game.orbitControls.enabled
  1261. if (!game.orbitControls.enabled) {
  1262. console.log(`position:`, game.camera.position)
  1263. console.log(`focus:`, game.orbitControls.target)
  1264. moveToRoom(stageData.currentRoom)
  1265. keyHistory = []
  1266. }
  1267. }
  1268. if (game.keyboard['Escape']) {
  1269. returnToMainMenu(game, stageData)
  1270. keyHistory = []
  1271. }
  1272. keyHistory.push(code.replace("Key", ""))
  1273. const cheatcode = keyHistory.join("").toLowerCase()
  1274. if(cheatcode.includes("ghostbux")) {
  1275. keyHistory = []
  1276. stageData.currency += 1000
  1277. addAmountToSave("currency", 1000)
  1278. updateGameStatusUI(game, stageData)
  1279. stageData.soundEffects['audio/witch_cackle1.ogg'].play()
  1280. }
  1281. if(cheatcode.includes("awesomesauce")) {
  1282. keyHistory = []
  1283. stageData.potionInventory.push(...stageData.potionInfo.map(info => info.name))
  1284. addValueToSave(stageData.potionInventory, "potion-inventory", "spooksauce")
  1285. stageData.soundEffects['audio/witch_cackle1.ogg'].play()
  1286. }
  1287. if(cheatcode.includes("yeschef")) {
  1288. keyHistory = []
  1289. //TODO: grant all ingredients
  1290. stageData.soundEffects['audio/witch_cackle1.ogg'].play()
  1291. }
  1292. }
  1293. export function returnToMainMenu(game, stageData) {
  1294. Howler.stop()
  1295. closeBrewUI(game, stageData)
  1296. closeShopUI(game, stageData)
  1297. hideNavigationUI(game, stageData)
  1298. openMainMenuUI(game, stageData)
  1299. hideGameStatusUI(game, stageData)
  1300. hideOptionsUI(game, stageData)
  1301. hideCreditsUI(game, stageData)
  1302. stageData.currentRoom = ROOM_BREW
  1303. game.camera.position.copy(stageData.cameraPositions[3].camera)
  1304. game.lookAtFocus = stageData.cameraPositions[3].focus.clone()
  1305. stageData.brewTutorial1.material.opacity = 0
  1306. stageData.brewTutorial1.castShadow = false
  1307. stageData.brewTutorial1.alreadySeen = false
  1308. stageData.shopTutorial1.material.opacity = 0
  1309. stageData.shopTutorial1.castShadow = false
  1310. stageData.shopTutorial1.alreadySeen = false
  1311. stageData.shopTutorial2.material.opacity = 0
  1312. stageData.shopTutorial2.castShadow = false
  1313. stageData.shopTutorial2.alreadySeen = false
  1314. updatePotionShelfDisplay()
  1315. updateGameStatusUI(game, stageData)
  1316. }