poikilos

KivyGlops update - master e0371c6

Aug 27th, 2024
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 67.55 KB | None | 0 0
  1.  
  2. def update(self):
  3. VMSG = " (verbose message in update)"
  4. pgp = self.player_glop.properties
  5. dd = debug_dict
  6. sg = self.settings['globals']
  7. sw = self.settings['world']
  8. # KivyGlops.update is called by KivyGlopsWindow.*update*
  9. # such as update_glsl
  10. # super(KivyGlops, self).update()
  11. # region pre-bump ops
  12. # NOT: tried to move regions "pre-bump ops" and
  13. # "bump loop" to pyglops but didn't work well
  14. # print("coords:"+str(Window.mouse_pos))
  15. # see also asp and clip_top in init
  16. # screen_w_arc_theta = 32.0
  17. # # actual number is fromprojectionMatrix matrix
  18. # screen_h_arc_theta = 18.0
  19. # # actual number is from projectionMatrix matrix
  20.  
  21. global missing_bumper_warning_enable
  22. global missing_bumpable_warning_enable
  23. global missing_radius_warning_enable
  24. doneGIs = set()
  25. failsafe = False
  26. if failsafe:
  27. sg = {
  28. 'camera_perspective_number': self.CAMERA_FIRST_PERSON(),
  29. }
  30. sw = {
  31. 'gravity': 9.8,
  32. 'ground': 0.0,
  33. 'friction_divisor': 1.2, # a.k.a. wfd
  34. }
  35. for a_i_i in range(0, len(self._actor_indices)):
  36. a_index = self._actor_indices[a_i_i]
  37. if a_i_i in doneGIs:
  38. raise RuntimeError("{} is in _actor_indices more than"
  39. " once.".format(a_i_i))
  40. doneGIs.add(a_i_i)
  41. if a_index is None:
  42. continue
  43. actor_glop = self.glops[a_index]
  44. ags = actor_glop.state
  45. agp = actor_glop.properties
  46. agad = actor_glop.actor_dict
  47. a_name = actor_glop.name
  48. if agad is None:
  49. print("[ KivyGlops ] error in update: "
  50. "actor_dict is None for bumper named '"
  51. + str(actor_glop.name) + "'")
  52. continue
  53. if agad.get("ai_enable") is not None:
  54. self.on_process_ai(a_index)
  55. # NOTE: moveto_index and target_index are guaranteed
  56. # to exist by set_as_actor_at
  57. if agad['target_index'] is not None:
  58. agad['target_pos'] = \
  59. self.glops[agad['target_index']]._t_ins.xyz
  60. elif agad['moveto_index'] is not None:
  61. targetG = self.glops[agad['moveto_index']]
  62. if not targetG.state['visible_enable']:
  63. agad['moveto_index'] = None
  64. if get_verbose_enable():
  65. print("[ KivyGlops ] (verbose message)"
  66. " actor lost target since glop at"
  67. " moveto_index is now invisible")
  68. else:
  69. agad['target_pos'] = targetG._t_ins.xyz
  70. if agad['target_pos'] is not None:
  71. ags['acquire_radius'] = agp['reach_radius']
  72. src_pos = actor_glop._t_ins.xyz
  73. dst_pos = agad['target_pos']
  74. # acquire_radius is changed below if ranged weapon
  75. distance = get_distance_vec3_xz(src_pos, dst_pos)
  76. ags['desired_use'] = None
  77. ags['choice_ii'] = -1 # inventory index
  78. if agad.get('target_index') is not None:
  79. weapon_index = None
  80. # NOTE: uses is determined by item_dict,
  81. # ranges is by actor_dict (unless use contains
  82. # "shoot_", then ranges are determined by
  83. # item_dict)
  84. # Start desired_* as None in case item is no
  85. # longer in inventory.
  86. agadII = agad['inventory_index']
  87. if agadII >= 0:
  88. try_item = agad['inventory_items'][agadII]
  89. if 'uses' in try_item:
  90. for this_use in try_item['uses']:
  91. if this_use in sg['attack_uses']:
  92. ags['desired_use'] = this_use
  93. # attack guarantees
  94. # attack_types exists
  95. # (via set_as_item)
  96. ags['choice_ii'] = agadII
  97. # ^ guaranteed to exist by
  98. # set_as_actor_at
  99. # TODO: loop again and look for melee
  100. # else item has no use
  101. if agad['choice_ii'] < 0:
  102. # If weapon is not selected, choose
  103. # random weapon even if selected a slot.
  104. dii, du = actor_glop.find_item_with_any_use(
  105. sg['attack_uses']
  106. )
  107. ags['choice_ii'] = dii
  108. ags['desired_use'] = du
  109. if ags['choice_ii'] >= 0:
  110. if "shoot_" in this_use:
  111. range_for_use = None
  112. ranges_for_it = try_item.get('ranges')
  113. if ranges_for_it is not None:
  114. range_for_use = \
  115. ranges_for_it.get(this_use)
  116. if ranges_for_it is not None:
  117. ags['acquire_radius'] = range_for_use
  118. else:
  119. # TODO: predict arc to determine
  120. # range instead
  121. ags['acquire_radius'] = 20.
  122. if get_verbose_enable():
  123. print(
  124. "[ KivyGlops ]" + VMSG
  125. + " used default acquire"
  126. " radius "
  127. + str(ags['acquire_radius'])
  128. + " since item['ranges']['"
  129. "{}'] wasn't set"
  130. "".format(this_use)
  131. )
  132. else:
  133. if this_use in agad['ranges']:
  134. ags['acquire_radius'] = \
  135. agad['ranges'][this_use]
  136. else:
  137. # TODO: predict arc to determine
  138. # range instead
  139. ags['acquire_radius'] = 20.
  140. if get_verbose_enable():
  141. print(
  142. "[ KivyGlops ]"
  143. + VMSG + " used"
  144. " default acquire"
  145. " radius "
  146. + str(ags['acquire_radius'])
  147. + " since"
  148. " actor_dict['ranges']['"
  149. + "{}'] wasn't set"
  150. "".format(this_use)
  151. )
  152. else:
  153. ags['acquire_radius'] = agp['reach_radius']
  154. # ACTUAL MOVEMENT is done further down,
  155. # in `region choice-based movement and physics`
  156. # end for a_i_i (actor)
  157. self.on_update_glops()
  158. # endregion pre-bump ops
  159.  
  160. # NOTE: (ANOTHER non-nested LOOP is at end of update,
  161. # for physics and unit movement)
  162.  
  163. # region nested bump loop
  164. for detectable_i_i in range(0, len(self._bumpable_indices)):
  165. bumpable_index = self._bumpable_indices[detectable_i_i]
  166. if bumpable_index is None:
  167. continue
  168. d_glop = self.glops[bumpable_index]
  169. # ^ item_glop (d for detected, formerly e for bumpee)
  170. # For old variable names see
  171. # <https://github.com/poikilos/KivyGlops/blob/
  172. # 9d3b64faf255869cb94de67114fef35a616bb95e/kivyglops.py>.
  173. dgn = d_glop.name
  174. # ^ bumpable_name (detected glop name)
  175. dgp = d_glop.properties
  176. dgs = d_glop.state
  177. if not dgp['bump_enable']:
  178. continue
  179. for bumper_i_i in range(0, len(self._bumper_indices)):
  180. bumper_index = self._bumper_indices[bumper_i_i]
  181. if bumper_index is None:
  182. continue
  183. actor_glop = self.glops[bumper_index]
  184. bgp = actor_glop.properties
  185. bgn = actor_glop.name
  186. # ^ bumper_name (formerly r for bumper)
  187. distance = get_distance_kivyglops(d_glop, actor_glop)
  188. if dgp['hit_radius'] is None:
  189. if missing_radius_warning_enable:
  190. print("[ KivyGlops ] WARNING in update: Missing"
  191. " radius while bumped bumpable named "
  192. + str(dgn))
  193. missing_radius_warning_enable = False
  194. continue
  195. total_hit_radius = 0.0
  196. if d_glop.projectile_dict is not None:
  197. total_hit_radius = (
  198. dgp['hit_radius'] + bgp['hit_radius']
  199. )
  200. else:
  201. try:
  202. total_hit_radius = (
  203. dgp['hit_radius'] + bgp['reach_radius']
  204. )
  205. except KeyError:
  206. total_hit_radius = dgp['hit_radius']
  207. print("ERROR in detectable_i_i loop:"
  208. " reach_radius is "
  209. + str(bgp.get('reach_radius'))
  210. + " for glop named " + bgn
  211. + " but actor's should never be None")
  212. if distance <= total_hit_radius:
  213. # print("total_hit_radius:" + str(total_hit_radius))
  214. if bumper_index in dgs['in_range_indices']:
  215. # print("not out of range yet")
  216. continue
  217. # (only bump if ever moved out of range of it)
  218. if bumper_index == bumpable_index:
  219. # can't bump self
  220. continue
  221. if get_verbose_enable():
  222. print("[ KivyGlops ]" + VMSG + "'"
  223. + str(bgn) + "' in range of '"
  224. + str(dgn) + "'")
  225. if bgp['bump_enable']:
  226. if ((d_glop.projectile_dict is None)
  227. or (bgp['hitbox'] is None)
  228. or hitbox_contains_vec3(bgp['hitbox'],
  229. d_glop._t_ins.xyz)):
  230. dgs['bumped_by_index'] = bumper_index
  231. dgs['at_rest_event_enable'] = True
  232. else:
  233. # global out_of_hitbox_note_enable
  234. # if out_of_hitbox_note_enable:
  235. print("[ KivyGlops ]"
  236. " (debug only--this"
  237. " is normal) within"
  238. " total_hit_radius,"
  239. " but detectable at "
  240. + str(d_glop.get_pos()) + " is"
  241. " not in bumper's"
  242. " hitbox: "
  243. + str(bgp['hitbox']))
  244. # out_of_hitbox_n
  245. # ote_enable = False
  246. else:
  247. if get_verbose_enable():
  248. print("[ KivyGlops ]"
  249. + VMSG + "'"
  250. + str(bgn)
  251. + "' is not a bumper.")
  252. if bumper_index not in dgs['in_range_indices']:
  253. dgs['in_range_indices'].append(bumper_index)
  254. else:
  255. if bumper_index in dgs['in_range_indices']:
  256. dgs['in_range_indices'].remove(bumper_index)
  257. # end for bumper
  258. # end for bumpable
  259. # endregion nested bump loop
  260. # (ANOTHER non-nested LOOP is at end of update,
  261. # for physics and unit movement)
  262.  
  263. # NOTE: hit detection above (such as item hitting enemy)
  264. # can make the item no longer bumpable or bumper,
  265. # so check for None:
  266. for j in reversed(range(len(self._bumpable_indices))):
  267. if self._bumpable_indices[j] is None:
  268. del(self._bumpable_indices[j])
  269. for j in reversed(range(len(self._bumper_indices))):
  270. if self._bumper_indices[j] is None:
  271. del(self._bumper_indices[j])
  272.  
  273. # region choice-based movement and physics
  274. # --in that order, so you don't go through stuff
  275. got_frame_delay = 0.0
  276. # ^ do NOT move this to anywhere before hit
  277. # detection is finished--otherwise
  278. # invisible movement could occur (ones
  279. # using got_frame_delay) before hit
  280. # detection
  281. if self.last_update_s is not None:
  282. got_frame_delay = best_timer() - self.last_update_s
  283. self.last_update_s = best_timer()
  284. if not self._delay_is_available_enable:
  285. # prevent useless work and 0 movement warnings
  286. # by stopping here if got_frame_delay 0 is expected
  287. self._delay_is_available_enable = True
  288. return
  289. pgi = self.get_player_glop_index(1)
  290. p1motivated = False
  291. for motivated_index in range(len(self.glops)):
  292. if motivated_index is None:
  293. continue
  294. p1_enable = False
  295. if motivated_index == pgi:
  296. p1_enable = True
  297. if p1motivated:
  298. raise RuntimeError("p1 was already moved")
  299. p1motivated = True
  300. m_glop = self.glops[motivated_index]
  301. mgs = m_glop.state
  302. mgp = m_glop.properties
  303. mgid = m_glop.item_dict
  304. mgad = m_glop.actor_dict
  305. sta = self.settings['templates']['actor']
  306. lups = None # land units per second
  307. if mgad is not None:
  308. lups = mgad.get('land_speed')
  309. if lups is None:
  310. lups = sta['land_speed']
  311. # land units per frame:
  312. land_units_this_frame = lups * got_frame_delay
  313. if land_units_this_frame <= 0.:
  314. land_units_this_frame = 0.
  315. global show_zero_walk_upf_warning_enable
  316. if show_zero_walk_upf_warning_enable:
  317. print("[ KivyGlops ] WARNING in update: zero "
  318. "land units per frame (" + tltf + ")")
  319. show_zero_walk_upf_warning_enable = False
  320.  
  321. laps = None # land acceleration units per second squared
  322. if mgad is not None:
  323. laps = mgad.get('land_accel')
  324. if laps is None:
  325. laps = sta['land_accel']
  326. lapf = laps * got_frame_delay # land accel per frame
  327.  
  328. ldps = None # land degrees per second
  329. if mgad is not None:
  330. ldps = mgad.get('land_degrees_per_second')
  331. if ldps is None:
  332. ldps = sta['land_degrees_per_second']
  333. # land radians per frame:
  334. lrpf = math.radians(ldps) * got_frame_delay
  335. if lrpf <= 0.:
  336. lrpf = 0.
  337. global show_zero_degrees_pf_warning_enable
  338. if show_zero_degrees_pf_warning_enable:
  339. print("[ KivyGlops ] WARNING in update: zero "
  340. "land degrees per frame (this is the last "
  341. "time this message will be shown)")
  342. show_zero_degrees_pf_warning_enable = False
  343.  
  344. # NOTE: Increased z should move object closer to viewer
  345. # in right-handed coordinate system
  346. choice_local_vel_mult = [0., 0., 0.]
  347. # ^ 1.0 is max joystick tilt: normally [0],[2]
  348. if 'dst_angles' not in mgs:
  349. mgs['dst_angles'] = None
  350. # mgs['look_theta_multipliers'] = [0., 0., 0.]
  351. mgas = m_glop.get_angles()
  352. if mgad is not None and mgad.get('target_pos') is not None:
  353. # If has target_pos, auto-move to target without
  354. # intervention even if is player-controlled glop.
  355. src_pos = m_glop.get_pos()
  356. dst_pos = mgad['target_pos']
  357. mgs['dst_angles'] = get_angles_vec3(
  358. src_pos,
  359. dst_pos,
  360. m_glop.get_angles()
  361. )
  362. distance = get_distance_vec3_xz(src_pos, dst_pos)
  363. tilt = .5
  364. run_enable = False
  365. sneak_enable = False
  366.  
  367. if mgs.get('acquire_radius') is not None:
  368. # if mgad['target_index'] is None:
  369. run_enable = True
  370. if run_enable:
  371. tilt *= 2.
  372. if sneak_enable:
  373. tilt /= 2.
  374. if distance > mgs['acquire_radius']:
  375. # # global velocity
  376. # vmx, vmy = get_rect_from_polar_rad(
  377. # tilt, mgas[1])
  378. # # use current y angle
  379. # # to prevent instant strafe
  380. # choice_local_vel_mult[0] = vmx
  381. # choice_local_vel_mult[2] = vmy
  382. # local velocity
  383. choice_local_vel_mult[2] = tilt
  384. if mgad['target_index'] is not None:
  385. # If has weapon and attack target, auto-attack
  386. # even if is player-controlled glop
  387. if mgs['choice_ii'] >= 0:
  388. try:
  389. self.use_item_at(
  390. m_glop,
  391. mgs['choice_ii'],
  392. this_use=mgs['desired_use']
  393. )
  394. except:
  395. print("[ KivyGlops ] "
  396. "ERROR in update--"
  397. "could not finish"
  398. " using item "
  399. + str(mgs.get('choice_ii')))
  400. view_traceback()
  401. else:
  402. if not mgad['unarmed_melee_enable']:
  403. mgad['target_index'] = None
  404. else:
  405. print("[ KivyGlops ] ERROR in update:"
  406. " 'target_pos' was set but the engine"
  407. " forgot to calculate 'acquire_radius'")
  408. elif p1_enable:
  409. # for keycode strings, see
  410. # http://kivy.org/docs/_modules/kivy/core/window.html
  411. # TODO: make a virtual joystick for touch, and
  412. # (set mgs['look_theta_multipliers'] or
  413. # do math right away and) set look_dest_theta
  414. # (and the longer you press before tilting, the faster
  415. # the speed; start moving automatically at .5 sec
  416. # OPTION 2: double-tap to not move--but start
  417. # accelerating immediately while down even then)
  418. tilt = .5
  419. if self.player1_controller._get_key_state_at(
  420. self.ui.get_keycode("ctrl")):
  421. tilt /= 2.
  422. if self.player1_controller._get_key_state_at(
  423. self.ui.get_keycode("shift")):
  424. tilt *= 2.
  425. if self.player1_controller._get_key_state_at(
  426. self.ui.get_keycode("a")):
  427. choice_local_vel_mult[0] = -1.
  428. # ^ full speed so same as virtual shoulder button
  429. elif self.player1_controller._get_key_state_at(
  430. self.ui.get_keycode('d')):
  431. choice_local_vel_mult[0] = 1.
  432. # ^ full speed so same as virtual shoulder button
  433. if self.player1_controller._get_key_state_at(
  434. self.ui.get_keycode("w")):
  435. # if get_verbose_enable():
  436. # chatter()
  437. # if self.get_fly_by_name(m_glop.name):
  438. # # intentionally use z,y:
  439. # vmz, vmy = get_rect_from_polar_rad(
  440. # tilt, m_glop._r_ins_x.angle)
  441. # choice_local_vel_mult[2] = vmz
  442. # choice_local_vel_mult[1] = vmy
  443. # else:
  444. choice_local_vel_mult[2] = tilt
  445. elif self.player1_controller._get_key_state_at(
  446. self.ui.get_keycode('b')):
  447. if get_verbose_enable():
  448. breakpoint()
  449.  
  450. elif self.player1_controller._get_key_state_at(
  451. self.ui.get_keycode('s')):
  452. # if self.get_fly_by_name(m_glop.name):
  453. # # intentionally use z,y:
  454. # opposite = math.radians(-180)
  455. # if m_glop._r_ins_x.angle < 0:
  456. # opposite *= -1.
  457. # vmz, vmy = get_rect_from_polar_rad(
  458. # tilt, m_glop._r_ins_x.angle + opposite)
  459. # choice_local_vel_mult[2] = vmz
  460. # choice_local_vel_mult[1] = vmy
  461. # else:
  462. choice_local_vel_mult[2] = -tilt
  463.  
  464. pstep(debug_dict,
  465. pre="player controlling " + m_glop.name)
  466. if self.player1_controller._get_key_state_at(
  467. self.ui.get_keycode("enter")):
  468. self.use_selected(m_glop)
  469.  
  470. if self.player1_controller._get_key_state_at(
  471. self.ui.get_keycode("spacebar")):
  472. if mgs['on_ground_enable']:
  473. # TODO: make double-jump event handler
  474. choice_local_vel_mult[1] = 1.
  475. # if get_verbose_enable():
  476. # print("[ KivyGlops ] (verbose message"
  477. # " in update: jumped (maximum try)")
  478. else:
  479. # if get_verbose_enable():
  480. # print("[ KivyGlops ] (verbose message"
  481. # " in update: can't jump while"
  482. # " not on ground.")
  483. pass
  484. # # DO NO MORE HIT DETECTION SINCE 1ST CHANGE IS BELOW
  485. # pstep(debug_dict, pre=("player controlling"
  486. # + self.glops[motivated_index].name))
  487. # ACTUAL MOVEMENT is done only if the object is at rest
  488. # (see else case below).
  489. check_pos_enable = False
  490. choice_moved_enable = False
  491. choice_world_vel = [0.0, 0.0, 0.0]
  492.  
  493. # if m_glop.look_target_glop is not None:
  494. # m_glop.look_at(m_glop.look_target_glop)
  495. # print(str(m_glop.name) + " looks at " +
  496. # str(m_glop.look_target_glop.name))
  497. # print(
  498. # " at " +
  499. # str(
  500. # get_vec3_from_point(self.camera_glop._t_ins))
  501. mgsv = None
  502. try:
  503. mgsv = mgs['velocity']
  504. except KeyError:
  505. raise KeyError("(FATAL) state template was not applied"
  506. " to glop named {} from file '{}' but"
  507. " physics-enabled glop must always have"
  508. " velocity".format(m_glop.name, m_glop.source_path)
  509. )
  510. ar_enable = False
  511. choice_world_vel_mult = None
  512. if mgs['on_ground_enable'] or \
  513. self.get_fly_by_name(m_glop.name):
  514. ar_enable = True
  515. # can control own movement
  516. # (do not use look_dest_theta directly since wasn't
  517. # turned all the way in that direction until after the
  518. # movement below could have taken place)
  519. # xz coords of edges of 16x16 square are:
  520. # move in the direction you are facing
  521.  
  522. choice_world_vel_mult = [0., 0., 0.]
  523. if choice_local_vel_mult[0] != 0.0 or \
  524. choice_local_vel_mult[1] != 0.0 or \
  525. choice_local_vel_mult[2] != 0.0:
  526. # makes movement relative to rotation
  527. # (which also limits speed when moving diagonally):
  528. moving_r_multiplier = \
  529. math.sqrt((choice_local_vel_mult[0]
  530. * choice_local_vel_mult[0])
  531. + (choice_local_vel_mult[2]
  532. * choice_local_vel_mult[2]))
  533. if moving_r_multiplier > 1.0:
  534. moving_r_multiplier = 1.0
  535. # Limited so that you can't move faster
  536. # when moving diagonally
  537. # print("[ KivyGlops ] WARNING in update:"
  538. # " clipped >100% movement")
  539. choice_world_vel_mult[0] = (moving_r_multiplier
  540. * math.cos(mgas[1]))
  541. # TODO: (?) make relative to rotation for fly mode:
  542. choice_world_vel_mult[1] = choice_local_vel_mult[1]
  543. choice_world_vel_mult[2] = (moving_r_multiplier
  544. * math.sin(mgas[1]))
  545. # choice_local* VARS SHOULD NOT BE USED AFTER THIS
  546. # SINCE THEY ARE NOT NEEDED FOR ANYTHING ELSE.
  547.  
  548. choice_world_r_vel = lapf * moving_r_multiplier
  549. radial_xz_velocity = (
  550. math.sqrt((mgsv[0] * mgsv[0])
  551. + (mgsv[2] * mgsv[2]))
  552. )
  553. if choice_world_r_vel + radial_xz_velocity < -lapf:
  554. choice_world_r_vel = 0.
  555. # choice_world_r_vel += (
  556. # (choice_world_r_vel +
  557. # radial_xz_velocity) -
  558. # lapf
  559. # )
  560. elif choice_world_r_vel + radial_xz_velocity > lapf:
  561. choice_world_r_vel = 0.
  562. # choice_world_r_vel -= (
  563. # (choice_world_r_vel +
  564. # radial_xz_velocity) -
  565. # lapf
  566. # )
  567. if choice_world_r_vel < kEpsilon:
  568. choice_world_r_vel = 0.0
  569. pstep(debug_dict, pre="m_glop " + m_glop.name)
  570. # TODO: reprogram so adding math.radians(-90)
  571. # is not needed (?) or remove these comments if
  572. # works now
  573. # choice_world_vel[0] = \
  574. # lapf*moving_r_multiplier * \
  575. # math.cos(
  576. # m_glop._r_ins_y.angle +
  577. # mgas[1] +
  578. # math.radians(-90))
  579. # choice_world_vel[1] = (lapf
  580. # * choice_world_vel_mult[1])
  581. # choice_world_vel[2] = \
  582. # lapf * moving_r_multiplier * \
  583. # math.sin(m_glop._r_ins_y.angle +
  584. # mgas[1] +
  585. # math.radians(-90))
  586. for a_i in range(3):
  587. choice_world_vel[a_i] = (
  588. choice_world_vel_mult[a_i]
  589. * lapf # land accel per frame
  590. )
  591. # choice_world_vel[a_i] = 0.0 # debug only
  592. totalDelta = get_distance_vec3(choice_world_vel,
  593. (0, 0, 0))
  594. if totalDelta > .1:
  595. print("WARNING: choice_world_vel is too large: "
  596. "{}".format(choice_world_vel))
  597. # ^ moving too fast
  598. # choice_world_vel[0] = (choice_world_r_vel
  599. # * math.cos(mgas[1])
  600. # )
  601. # choice_world_vel[1] = (lapf
  602. # * choice_world_vel_mult[1]
  603. # )
  604. # choice_world_vel[2] = (choice_world_r_vel
  605. # * math.sin(mgas[1])
  606. # )
  607. # if (m_glop._t_ins.x + move_by_x > \
  608. # self._world_cube.get_max_x()):
  609. # move_by_x = \
  610. # self._world_cube.get_max_x() - \
  611. # m_glop._t_ins.x
  612. # print(str(m_glop._t_ins.x) + " of max_x:" +
  613. # str(self._world_cube.get_max_x()))
  614. # if (m_glop._t_ins.z + move_by_z > \
  615. # self._world_cube.get_max_z()):
  616. # move_by_z = self._world_cube.get_max_z() - \
  617. # m_glop._t_ins.z
  618. # print(str(m_glop._t_ins.z) + " of max_z:" +
  619. # str(self._world_cube.get_max_z()))
  620. # if (m_glop._t_ins.x + move_by_x < \
  621. # self._world_cube.get_min_x()):
  622. # move_by_x = self._world_cube.get_min_x() - \
  623. # m_glop._t_ins.x
  624. # print(str(m_glop._t_ins.x) + " of max_x:" +
  625. # str(self._world_cube.get_max_x()))
  626. # if (m_glop._t_ins.z + move_by_z < \
  627. # self._world_cube.get_min_z()):
  628. # move_by_z = self._world_cube.get_min_z() - \
  629. # m_glop._t_ins.z
  630. # print(str(m_glop._t_ins.z) + " of max_z:" +
  631. # str(self._world_cube.get_max_z()))
  632.  
  633. # print(str(m_glop._t_ins.xz) + " each " +
  634. # "coordinate should be between matching" +
  635. # " one in " +
  636. # str(self._world_cube.get_min_x()) + "," +
  637. # str(self._world_cube.get_min_z()) +
  638. # " and " +
  639. # str(self._world_cube.get_max_x()) + "," +
  640. # str(self._world_cube.get_max_z()))
  641. # print(str(m_glop._t_ins.xyz) + " each " +
  642. # "coordinate should be between matching" +
  643. # " one in " +
  644. # str(self.world_boundary_min) +
  645. # " and " +
  646. # str(self.world_boundary_max))
  647. for axis_i in range(0, 3):
  648. if choice_world_vel[axis_i] != 0.0:
  649. choice_moved_enable = True
  650. mgsv[axis_i] += choice_world_vel[axis_i]
  651.  
  652. if mgsv[axis_i] != 0.0:
  653. # set _t_ins via set_coord:
  654. m_glop.set_coord(axis_i, mgsv[axis_i])
  655. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  656. # self.prev_inbounds_camera_translate = \
  657. # self.camera_glop._t_ins.x,
  658. # self.camera_glop._t_ins.y,
  659. # self.camera_glop._t_ins.z
  660.  
  661. # else:
  662. # self.camera_glop._t_ins.x += \
  663. # self.land_units_this_frame * \
  664. # choice_local_vel_mult[0]
  665. # self.camera_glop._t_ins.z += \
  666. # self.land_units_this_frame * \
  667. # choice_local_vel_mult[2]
  668.  
  669. # TODO:? if mgs['look_theta_multipliers'][1] != 0.0:
  670. # delta_y = lrpf * choice_try_theta_multipliers[1]
  671. # m_glop._r_ins_y.angle += delta_y
  672. # if choice_try_theta_multipliers is not None:
  673. # choice_world_turn_theta = \
  674. # choice_try_theta_multipliers[1]
  675.  
  676. if mgs['dst_angles'] is not None:
  677. # if land_units_this_frame is not None:
  678. for a_i in range(3):
  679. delta_theta = mgs['dst_angles'][a_i] - mgas[a_i]
  680. if delta_theta > lrpf:
  681. delta_theta = lrpf
  682. elif delta_theta < -lrpf:
  683. delta_theta = -lrpf
  684. # check kEpsilon to prevent jitter while stopped
  685. if delta_theta > kEpsilon or \
  686. delta_theta < -kEpsilon:
  687. new_a = mgas[a_i] + delta_theta
  688. m_glop.set_angle(a_i, new_a)
  689. if p1_enable and a_i == 1:
  690. if not fequals(m_glop.get_angle(a_i),
  691. new_a):
  692. # print(
  693. # "FAILED to set angle " +
  694. # str(math.degrees(
  695. # m_glop.get_angle(a_i))) +
  696. # " to " +
  697. # str(math.degrees(new_a)))
  698. print("FAILED to set angle "
  699. + str(m_glop.get_angle(a_i))
  700. + " to "
  701. + str(new_a))
  702. # TODO: m_glop._r_ins_y.angle = \
  703. # angle_trunc(m_glop._r_ins_y.angle)
  704. # m_glop._t_ins.x += \
  705. # choice_local_vel_mult[0]
  706. # m_glop._t_ins.z += \
  707. # choice_local_vel_mult[2]
  708. # else:
  709. # print("[ KivyGlops ] ERROR in update:"
  710. # " choice_world_turn_theta was set"
  711. # " for unit, but engine forgot to set"
  712. # " land_units_this_frame")
  713.  
  714. # end if on_ground_enable or flying can control own movement
  715. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  716. pcgs = None # player-controlled glop state
  717. if p1_enable:
  718. if sg['camera_perspective_number'] == \
  719. self.CAMERA_FIRST_PERSON():
  720. # player-controlled glop
  721. pcgs = self.player_glop.state
  722. else:
  723. pcgs = self.camera_glop.state
  724.  
  725. if pcgs is not None and \
  726. pcgs.get('dst_angles') is not None:
  727. if 'Player' not in debug_dict:
  728. debug_dict['Player'] = {}
  729. pcg = None
  730. if pcgs.get('glop_index') is not None:
  731. pcg = self.glops[pcgs['glop_index']]
  732. debug_dict['Player']['name'] = pcg.name
  733. debug_dict['Player']['angles'] = \
  734. fixed_width(
  735. degrees_list(
  736. pcg.get_angles()), 6, " ")
  737. debug_dict['Player']['dst_angles'] = \
  738. fixed_width(
  739. degrees_list(
  740. pcgs['dst_angles']), 6, " ")
  741. debug_dict['Player']['free'] = ar_enable
  742.  
  743. if choice_moved_enable:
  744. check_pos_enable = True
  745. # if (not mgs['on_ground_enable']) or \
  746. # choice_moved_enable:
  747. # if not mgs['on_ground_enable']:
  748. # if m_glop._cached_floor_y is None:
  749. # m_glop._cached_floor_y = self._world_min_y
  750. # # TODO: get from walkmesh instead and
  751. # # eliminate _cached_floor_y
  752. # (this part is under no outer conditions)
  753. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  754. if mgp['physics_enable']:
  755. # TODO: Fix issue where can't move if physics_enable is
  756. # false
  757. if mgs.get('show_physics_msg_enable') is None:
  758. if get_verbose_enable():
  759. print("[ KivyGlops ] (verbose message "
  760. "in update) processing first run of"
  761. " physics for " + m_glop.name)
  762. mgs['show_physics_msg_enable'] = True
  763. # walk_info = \
  764. # self.constrain_glop_to_walkmesh(m_glop)
  765. # on_ground_enable = \
  766. # walk_info.get('on_ground_enable')
  767. # if on_ground_enable is not None:
  768. # if mgs['on_ground_enable'] != \
  769. # on_ground_enable:
  770. # mgs['on_ground_enable'] = \
  771. # on_ground_enable
  772. # mgs['at_rest_event_enable'] = \
  773. # True
  774. # deprecated this_glop_free_enable = False
  775. # if m_glop._cached_floor_y is not None:
  776. # if m_glop._t_ins.y - mgp['hit_radius'] - \
  777. # kEpsilon > m_glop._cached_floor_y:
  778. # # this_glop_free_enable = True
  779. # pass
  780. # else: # STOP object
  781. # # (remove owner and projectile_dict)
  782. # mgs['on_ground_enable'] = True
  783. # else:
  784. # pass
  785. # # no cached floor, so move without regard to
  786. # # ground
  787. # # this_glop_free_enable = True
  788.  
  789. if mgs['at_rest_event_enable']:
  790. # HIT GROUND (or target if
  791. # mgs.get('bumped_by_index') \
  792. # is not None
  793. mgs['at_rest_event_enable'] = False
  794. bumper_index = mgs.get('bumped_by_index')
  795. d_glop = None
  796. r_glop = None
  797. egp = None
  798. rgp = None
  799. if bumper_index is not None:
  800. self.on_bump(motivated_index, bumper_index)
  801. bumpable_index = motivated_index
  802. d_glop = self.glops[bumpable_index]
  803. r_glop = self.glops[bumper_index]
  804. egp = d_glop.properties
  805. rgp = r_glop.properties
  806. else:
  807. self.on_bump_world(motivated_index, 'ground')
  808. bumper_index = motivated_index
  809. bumpable_index = None
  810. r_glop = self.glops[bumper_index]
  811. rgp = r_glop.properties
  812. # TODO: optionally, such as for bottom-heavy
  813. # items: m_glop._r_ins_x.angle = 0.
  814. # if mgsv[2] > kEpsilon:
  815. # if (mgsv[1] < 0.0 - \
  816. # (kEpsilon + mgp['hit_radius'])):
  817. # print(" HIT GROUND Y:" +
  818. # str(m_glop._cached_floor_y))
  819. # bump_sound_paths is guaranteed by PyGlop
  820. # _init_glop to exist in glop's properties
  821. if d_glop is not None:
  822. bsps = egp['bump_sound_paths']
  823. if len(bsps) > 0:
  824. rand_i = random.randrange(
  825. 0, len(bsps))
  826. self.play_sound(bsps[rand_i])
  827. igpd = d_glop.projectile_dict
  828. # NOTE: already checked
  829. # bumpable_index bump_enable above
  830. # print("distance:" + str(total_hit_radius) +
  831. # " <= total_hit_radius:" +
  832. # str(total_hit_radius))
  833. if igpd is None or \
  834. ('owner' not in igpd) or \
  835. (igpd['owner'] != r_glop.name):
  836. self._internal_bump_glop(bumpable_index,
  837. bumper_index)
  838. if get_verbose_enable():
  839. if d_glop is not None:
  840. print("[ KivyGlops ]" + VMSG
  841. + str(r_glop.name)
  842. + " bumped "
  843. + str(d_glop.name))
  844. elif r_glop is not None:
  845. print("[ KivyGlops ]" + VMSG
  846. + str(r_glop.name)
  847. + " bumped world")
  848. else:
  849. if get_verbose_enable():
  850. print("[ KivyGlops ]" + VMSG
  851. + "cannot bump own projectile")
  852.  
  853. # NOTE: projectile_dict is already removed above
  854. # by _internal_bump_glop if relevant
  855. if mgid is not None:
  856. if mgid['state'].get('owner') is not None:
  857. del mgid['state']['owner']
  858. if mgid['state'].get('owner_key') is not None:
  859. del mgid['state']['owner_key']
  860.  
  861. # m_glop._t_ins.y = m_glop._cached_floor_y +
  862. # mgp['hit_radius']
  863. # check_pos_enable = True
  864. # if mgsv[0] != 0. or \
  865. # mgsv[1] != 0. or \
  866. # mgsv[2] != 0.:
  867. # if get_verbose_enable():
  868. # print("[ KivyGlops ] stopped glop" +
  869. # "{hit_radius:" +
  870. # str(mgp['hit_radius']) +
  871. # "; glop._cached_floor_y:" +
  872. # str(m_glop._cached_floor_y) +
  873. # "}")
  874. mgsv[1] = 0.0
  875. # end if mgs['at_rest_event_enable']
  876. # (still inside `if...physics_enable`--and only that)
  877. if mgs['on_ground_enable']:
  878. wfd = sw['friction_divisor']
  879. wfdp = wfd
  880. if mgsv[1] < -kEpsilon:
  881. wfdp = wfd + -mgsv[1]
  882. # ^ pressure increases friction
  883. # TODO: real physics for wfdp
  884. if mgsv[1] <= kEpsilon:
  885. # if no upward velocity, do friction
  886. if mgsv[0] > kEpsilon:
  887. mgsv[0] /= wfdp
  888. else:
  889. mgsv[0] = 0.
  890. # mgsv[1] is done later,
  891. # based on gravity
  892. if mgsv[2] > kEpsilon:
  893. mgsv[2] /= wfdp
  894. else:
  895. mgsv[2] = 0.
  896. # this_glop_free_enable = False
  897. src_pos = m_glop.get_pos()
  898. dst_pos = (
  899. src_pos[0] + mgsv[0] * got_frame_delay,
  900. src_pos[1] + mgsv[1] * got_frame_delay,
  901. src_pos[2] + mgsv[2] * got_frame_delay
  902. )
  903. '''
  904. if get_verbose_enable():
  905. print("CHANGING {} dst_pos to {} using src_pos {}"
  906. " + mgsv {} * {}..."
  907. "".format(m_glop.name, dst_pos, src_pos, mgsv,
  908. got_frame_delay))
  909. '''
  910. if get_verbose_enable():
  911. if mgad is not None and mgp['roll_enable']:
  912. print("[ KivyGlops ] WARNING in update:"
  913. " roll_enable is True for actor"
  914. " '{}'".format(m_glop.name))
  915.  
  916. if mgs['on_ground_enable'] and \
  917. (mgp.get('hit_radius') is not None) and \
  918. (mgp['hit_radius'] > 0) and \
  919. mgp['roll_enable']:
  920. # ^ roll only if not actor (mgad is None)
  921. # TODO: Use rolling friction (here or elsewhere)
  922. # TODO: Project it into object space for accuracy
  923. angles = m_glop.get_angles()
  924. rolling_vec_indices = (0, 2)
  925. rvtis = (2, 1) # rolling vector theta indices
  926. rvps = ((0, 2), (1, 2)) # rolling vector planes
  927. for rvi in rolling_vec_indices:
  928. src_2D_pos = (src_pos[rvps[rvi][0]],
  929. src_pos[rvps[rvi][1]])
  930. dst_2D_pos = (dst_pos[rvps[rvi][0]],
  931. dst_pos[rvps[rvi][1]])
  932. # first do trig to get angle from pos delta:
  933. offset_theta = get_angle_vec2(src_2D_pos,
  934. dst_2D_pos)
  935. # <https://www.mathopenref.com/arclength.html>
  936. al = (TAU * mgp['hit_radius'] *
  937. (offset_theta / TAU))
  938. # Simplifies if have radians & central angle
  939. # but central angle is always acute
  940. # so doesn't provide info useful to engine:
  941. # al = mgp['hit_radius'] * offset_c
  942. angles[rvi] += al
  943. # TODO: why does changing rotation
  944. # make things hit ground too high?
  945. if (angles[rvi] > TAU):
  946. angles[rvi] -= TAU
  947. elif (angles[rvi] < NEG_TAU):
  948. angles[rvi] += TAU
  949. m_glop.set_angles(angles)
  950. # do even if 'on_ground_enable' since may be rolling
  951. m_glop.set_pos(dst_pos)
  952. debugKey = m_glop.name
  953. if debugKey == "Player 1":
  954. debugKey = "Player"
  955. if debugKey not in debug_dict:
  956. debug_dict[debugKey] = {}
  957. debug_dict[debugKey]['pos'] = m_glop.get_pos()
  958. if not mgs['on_ground_enable']:
  959. # process gravity only
  960. # (don't do hit detection again until user
  961. # [& ai at top of this method] sees this frame)
  962. if got_frame_delay > 0.0:
  963. check_pos_enable = True
  964. # print("[ KivyGlops ]" + VMSG +
  965. # "GRAVITY AFFECTED:" +
  966. # str(m_glop._t_ins.y) +
  967. # " += " + str(mgsv[1]))
  968. mgsv[1] -= sw['gravity'] * got_frame_delay
  969. # print("[ KivyGlops ]" + VMSG +
  970. # "THEN VELOCITY CHANGED TO:" +
  971. # str(mgsv[1]))
  972. # print("[ KivyGlops ]" + VMSG +
  973. # "FRAME INTERVAL:" +
  974. # str(got_frame_delay))
  975. else:
  976. if self._delay_is_available_enable:
  977. print("[ KivyGlops ] "
  978. "WARNING in update: no frame"
  979. " delay is detectable (update"
  980. " normally runs automatically"
  981. " once per frame but seems to"
  982. " be running more often)")
  983. # end if physics_enable
  984. # AND FORMERLY end on_ground_enable or choice_moved_enable
  985. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  986. # if choice_local_vel_mult[0] != 0.0 or \
  987. # # choice_local_vel_mult[1] != 0.0 or \
  988. # # choice_local_vel_mult[2] != 0.0:
  989. # did NOT necessarily move (deltas already checked)
  990. if (not mgs['on_ground_enable']):
  991. if choice_world_vel[0] != 0.0 or \
  992. choice_world_vel[1] != 0.0 or \
  993. choice_world_vel[2] != 0.0:
  994. # then already did check_pos_enable when set
  995. if get_verbose_enable():
  996. prev_on_ground_enable = \
  997. mgs.get('prev_on_ground_enable')
  998. if prev_on_ground_enable != \
  999. mgs['on_ground_enable']:
  1000. print("[ KivyGlops ]" + VMSG
  1001. + "glop " + m_glop.name
  1002. + " tried to move, but was not "
  1003. "at rest (physics in control)")
  1004.  
  1005. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  1006. '''
  1007. # Confirmed: choice_world_vel and choice_world_vel_mult
  1008. # only change for the player.
  1009. dN = "glop[{}]".format(motivated_index)
  1010. if pgi == motivated_index:
  1011. dN += " (player)"
  1012. debug_dict[dN] = {}
  1013. ddG = debug_dict[dN]
  1014. ddG['choice_world_vel'] = \
  1015. choice_world_vel
  1016. ddG['choice_world_vel_mult'] = \
  1017. choice_world_vel_mult
  1018. # ^ None unless controlled above (such as player 1)
  1019. '''
  1020.  
  1021.  
  1022. mgs['prev_on_ground_enable'] = mgs['on_ground_enable']
  1023. mgs['constrained_enable'] = False
  1024. # deprecated this_glop_free_enable
  1025. # deprecated stop_this_bumpable_enable
  1026. for rel in mgs['links']:
  1027. if rel['r_type'] == "carry":
  1028. if m_glop._t_ins.xyz != \
  1029. rel['state']['parent_glop']._t_ins.xyz:
  1030. m_glop._t_ins.x = \
  1031. rel['state']['parent_glop']._t_ins.x
  1032. m_glop._t_ins.y = \
  1033. rel['state']['parent_glop']._t_ins.y
  1034. m_glop._t_ins.z = \
  1035. rel['state']['parent_glop']._t_ins.z
  1036. check_pos_enable = True
  1037. mgs['on_ground_enable'] = True
  1038. mgs['constrained_enable'] = True
  1039. else:
  1040. print("[ KivyGlops ] ERROR in update: "
  1041. "unknown link r_type "
  1042. + str(rel.get('r_type')))
  1043. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  1044. # if mgp['physics_enable']:
  1045. if p1_enable:
  1046. if 'Player' not in dd:
  1047. dd['Player'] = {}
  1048. dd['Player']['check_pos_enable'] = check_pos_enable
  1049. if check_pos_enable and mgp['clip_enable']:
  1050. const_ground_enable = True
  1051. walk_info = None
  1052. walkmesh_enable = True
  1053. # ^ becomes False below if there are no walkmeshes
  1054. if walkmesh_enable:
  1055. if len(self._walkmeshes) > 0:
  1056. const_ground_enable = False
  1057. # constrained_pos = [m_glop._t_ins.x,
  1058. # m_glop._t_ins.y,
  1059. # m_glop._t_ins.z]
  1060. if mgp['hitbox'] is not None:
  1061. walk_info = self.get_walk_info(
  1062. m_glop._t_ins.xyz,
  1063. (mgp['hitbox']['maximums'][0],
  1064. -mgp['hitbox']['minimums'][1])
  1065. )
  1066. else:
  1067. walk_info = self.get_walk_info(
  1068. m_glop._t_ins.xyz,
  1069. (mgp['hit_radius'],
  1070. mgp['hit_radius'])
  1071. )
  1072. if (motivated_index
  1073. == self.get_player_glop_index(1)):
  1074. if 'Player' not in dd:
  1075. dd['Player'] = {}
  1076. dd['Player']['walkmesh_via'] = \
  1077. walk_info['walkmesh_via']
  1078. dd['Player']['feet_y'] = walk_info['feet_y']
  1079.  
  1080. else:
  1081. walkmesh_enable = False
  1082. if const_ground_enable:
  1083. walk_info = {}
  1084. walk_info['pos'] = [
  1085. m_glop._t_ins.x,
  1086. m_glop._t_ins.y,
  1087. m_glop._t_ins.z
  1088. ]
  1089. walk_info['change_enable'] = False
  1090. height_only_enable = True
  1091. corrected_pos = [
  1092. m_glop._t_ins.x,
  1093. m_glop._t_ins.y,
  1094. m_glop._t_ins.z
  1095. ]
  1096. if corrected_pos[1] < sw['ground']:
  1097. corrected_pos[1] = sw['ground']
  1098. hit_ground_enable = None
  1099. if not height_only_enable:
  1100. walk_info['change_enable'] = True
  1101. walk_info['pos'][0] = corrected_pos[0]
  1102. walk_info['pos'][2] = corrected_pos[2]
  1103. # TODO: check y (vertical) axis against
  1104. # eye height and jump height etc
  1105. # region pasted from get_walk_info
  1106. if walk_info['pos'][1] - corrected_pos[1] < \
  1107. kEpsilon:
  1108. walk_info['on_ground_enable'] = True
  1109. elif walk_info['pos'][1] - corrected_pos[1] > \
  1110. kEpsilon:
  1111. # Hovering higher than kEpsilon--
  1112. # use kEpsilon as a deadzone so that
  1113. # floating point errors don't cause physics
  1114. # and hence many at_rest events
  1115. walk_info['on_ground_enable'] = False
  1116.  
  1117. if corrected_pos[1] > walk_info['pos'][1]:
  1118. walk_info['change_enable'] = True
  1119. walk_info['pos'][1] = corrected_pos[1]
  1120. else:
  1121. # Hovering (previous if-else flags for physics)
  1122. pass
  1123. # endregion pasted from get_walk_info
  1124. elif not walkmesh_enable:
  1125. raise NotImplementedError(
  1126. "Only walkmesh and const_ground_enable"
  1127. " walk_info are implemented."
  1128. )
  1129. walk_info = {}
  1130. walk_info['on_ground_enable'] = True
  1131. walk_info['change_enable'] = False
  1132. if get_verbose_enable():
  1133. print("walkmesh_enable: {}".format(walkmesh_enable))
  1134.  
  1135. on_ground_enable = walk_info.get('on_ground_enable')
  1136. if on_ground_enable is not None:
  1137. if mgs['on_ground_enable'] != on_ground_enable:
  1138. mgs['on_ground_enable'] = on_ground_enable
  1139. if on_ground_enable:
  1140. mgs['at_rest_event_enable'] = True
  1141. # frame of hit is shown to player and ai
  1142. # BEFORE event is handled
  1143. else:
  1144. pass
  1145. # mgs['not_at_rest_event_enable'] = True
  1146. # TODO: (?) make an on_not_at_rest event
  1147. if walk_info['change_enable']:
  1148. if get_verbose_enable():
  1149. print("{} walk_info:{}"
  1150. "".format(m_glop.name, walk_info))
  1151. # frame of hit is shown to player and ai
  1152. # BEFORE event is handled
  1153. m_glop._t_ins.x = walk_info['pos'][0]
  1154. # if on_ground_enable is True:
  1155. m_glop._t_ins.y = walk_info['pos'][1]
  1156. m_glop._t_ins.z = walk_info['pos'][2]
  1157. # end for motivated_index in glops
  1158. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  1159. # movitated_glop out of scope
  1160. # for index in self._bumper_indices:
  1161. # m_glop = self.glops[index]
  1162. # walk_info = self.constrain_glop_to_walkmesh(m_glop)
  1163. # on_ground_enable = walk_info.get('on_ground_enable')
  1164. # if on_ground_enable is not None:
  1165. # if mgs['on_ground_enable'] != on_ground_enable:
  1166. # mgs['on_ground_enable'] = on_ground_enable
  1167. # print(
  1168. # "[ KivyGlops ] WARNING: update changed" +
  1169. # " rest state of " + m_glop.name + " to " +
  1170. # str(on_ground_enable) + " but at_rest " +
  1171. # "events were not fired nor was manual" +
  1172. # " programming done (not yet implemented)")
  1173. # endregion choice-based movement and physics
  1174.  
  1175. if sg['camera_perspective_number'] == \
  1176. self.CAMERA_FIRST_PERSON():
  1177. self.camera_glop._t_ins.x = self.player_glop._t_ins.x
  1178. self.camera_glop._t_ins.y = (self.player_glop._t_ins.y
  1179. + pgp['eye_height'])
  1180. self.camera_glop._t_ins.z = self.player_glop._t_ins.z
  1181. self.camera_glop._r_ins_x.angle = \
  1182. self.player_glop._r_ins_x.angle
  1183. self.camera_glop._r_ins_y.angle = \
  1184. self.player_glop._r_ins_y.angle
  1185. self.camera_glop._r_ins_z.angle = \
  1186. self.player_glop._r_ins_z.angle
  1187. elif sg['camera_perspective_number'] == self.CAMERA_FREE():
  1188. pass
  1189. else:
  1190. print("[ KivyGlops ] ERROR in update:"
  1191. " settings['camera_perspective_number'] {}"
  1192. " is not yet implemented. Try setting number to "
  1193. " in scene to one of the self.CAMERA_*()"
  1194. " methods' returns."
  1195. "".format(sg['camera_perspective_number']))
  1196. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  1197. asp = float(self.ui.width) / float(self.ui.height)
  1198.  
  1199. clip_top = 0.06 # NOTE: 0.03 is ~1.72 degrees, if that matters
  1200. # formerly field_of_view_factor
  1201. # was changed to .03 when projection_near was changed from
  1202. # 1 to .1
  1203. # was .3 when projection_near was 1
  1204.  
  1205. clip_right = asp*clip_top # formerly overwrote asp
  1206. self.projectionMatrix = Matrix()
  1207. self.modelViewMatrix = Matrix()
  1208.  
  1209. # self.modelViewMatrix.rotate(
  1210. # self.camera_glop._r_ins_x.angle,1.0,0.0,0.0)
  1211. # self.modelViewMatrix.rotate(
  1212. # self.camera_glop._r_ins_y.angle,0.0,1.0,0.0)
  1213. # look_at(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY,
  1214. # upZ) # http://kivy.org/docs/
  1215. # # api-kivy.graphics.transformation.html
  1216. # self.modelViewMatrix.rotate(self.camera_glop._r_ins_z.angle,
  1217. # 0.0, 0.0, 1.0)
  1218. previous_look_point = None
  1219. if self.look_point is not None:
  1220. previous_look_point = (
  1221. self.look_point[0],
  1222. self.look_point[1],
  1223. self.look_point[2]
  1224. )
  1225.  
  1226. self.look_point = [0.0, 0.0, 0.0]
  1227.  
  1228. # 0 is the angle (1, 2, and 3 are the matrix)
  1229. self.look_point[0] = \
  1230. (self.focal_distance
  1231. * math.cos(self.camera_glop._r_ins_y.angle))
  1232. self.look_point[2] = \
  1233. (self.focal_distance
  1234. * math.sin(self.camera_glop._r_ins_y.angle))
  1235. # print("self.camera_glop._r_ins_y.angle: "
  1236. # + str(self.camera_glop._r_ins_y.angle))
  1237.  
  1238. # self.look_point[1] = 0.0
  1239. # ^ (changed in "for" loop below) since y is up, and 1 is y,
  1240. # ignore index 1 when we are rotating on that axis
  1241. self.look_point[1] = \
  1242. (self.focal_distance
  1243. * math.sin(self.camera_glop._r_ins_x.angle))
  1244.  
  1245. # self.modelViewMatrix = self.modelViewMatrix.look_at(
  1246. # 0, self.camera_glop._t_ins.y,0, self.look_point[0],
  1247. # self.look_point[1], self.look_point[2], 0, 1, 0)
  1248.  
  1249. # Since camera's target should be relative to camera,
  1250. # add camera's position:
  1251.  
  1252. self.look_point[0] += self.camera_glop._t_ins.x
  1253. self.look_point[1] += self.camera_glop._t_ins.y
  1254. self.look_point[2] += self.camera_glop._t_ins.z
  1255.  
  1256. # must translate first, otherwise look_at will override
  1257. # position on rotation axis ('y' in this case)
  1258. self.modelViewMatrix.translate(self.camera_glop._t_ins.x,
  1259. self.camera_glop._t_ins.y,
  1260. self.camera_glop._t_ins.z)
  1261. self.modelViewMatrix = self.modelViewMatrix.look_at(
  1262. self.camera_glop._t_ins.x,
  1263. self.camera_glop._t_ins.y,
  1264. self.camera_glop._t_ins.z,
  1265. self.look_point[0],
  1266. self.look_point[1],
  1267. self.look_point[2],
  1268. 0,
  1269. 1,
  1270. 0
  1271. )
  1272.  
  1273. # projectionMatrix.
  1274. # view_clip(left, right, bottom, top, near, far, perspective)
  1275. # "In OpenGL, a 3D point in eye space is projected onto the
  1276. # near plane (projection plane)"
  1277. # -http://www.songho.ca/opengl/gl_projectionmatrix.html
  1278. # The near plane and far plane distances are in the -z direction
  1279. # but are expressed as positive values since they are distances
  1280. # from the camera then they are compressed to -1 to 1
  1281. # -https://www.youtube.com/watch?v=frtzb2WWECg
  1282. self.projectionMatrix = self.projectionMatrix.view_clip(
  1283. -clip_right, clip_right, -1*clip_top, clip_top,
  1284. self.projection_near,
  1285. 100, # far
  1286. 1, # perspective
  1287. )
  1288. top_theta = theta_radians_from_rectangular(
  1289. self.projection_near, clip_top)
  1290. right_theta = theta_radians_from_rectangular(
  1291. self.projection_near, clip_right)
  1292. self.ui.screen_w_arc_theta = right_theta*2.0
  1293. self.ui.screen_h_arc_theta = top_theta*2.0
  1294.  
  1295. glwCv = self.ui.gl_widget.canvas
  1296. glwCv['projection_mat'] = self.projectionMatrix
  1297. glwCv['modelview_mat'] = self.modelViewMatrix
  1298. glwCv['camera_world_pos'] = self.camera_glop._t_ins.xyz
  1299.  
  1300. # if get_verbose_enable():
  1301. # Logger.debug("ok (update_glsl)")
  1302. # is_look_point_changed = False
  1303. # if previous_look_point is not None:
  1304. # for axis_index in range(3):
  1305. # if self.look_point[axis_index] != \
  1306. # previous_look_point[axis_index]:
  1307. # is_look_point_changed = True
  1308. # # print(str(self.look_point) + " was " +
  1309. # # str(previous_look_point))
  1310. # break
  1311. # else:
  1312. # is_look_point_changed = True
  1313. # if is_look_point_changed:
  1314. # pass
  1315. # # print("Now looking at " + str(self.look_point))
  1316. # # print(
  1317. # # "position: " +
  1318. # # str(get_vec3_from_point(self.camera_glop._t_ins)" +
  1319. # # "; self.camera_glop._r_ins_y.angle:" +
  1320. # # str(self.camera_glop._r_ins_y.angle) +
  1321. # # "(" +
  1322. # # str(math.degrees(self.camera_glop._r_ins_y.angle)) +
  1323. # # "degrees); moving_theta:" +
  1324. # # str(math.degrees(moving_theta)) +
  1325. # # " degrees")
  1326.  
  1327. if ((self._previous_world_light_dir is None)
  1328. or (self._previous_world_light_dir[0]
  1329. != glwCv['_world_light_dir'][0])
  1330. or (self._previous_world_light_dir[1]
  1331. != glwCv['_world_light_dir'][1])
  1332. or (self._previous_world_light_dir[2]
  1333. != glwCv['_world_light_dir'][2])
  1334. or (self._previous_camera_rotate_y_angle is None)
  1335. or (self._previous_camera_rotate_y_angle
  1336. != self.camera_glop._r_ins_y.angle)):
  1337. # glwCv['_world_light_dir'] = (0.0, .5, 1.0)
  1338. # glwCv['_world_light_dir_eye_space'] = (0.0, .5, 1.0)
  1339. world_light_theta = theta_radians_from_rectangular(
  1340. glwCv['_world_light_dir'][0],
  1341. glwCv['_world_light_dir'][2]
  1342. )
  1343. light_theta = (world_light_theta
  1344. + self.camera_glop._r_ins_y.angle)
  1345. light_r = math.sqrt(
  1346. (glwCv['_world_light_dir'][0]
  1347. * glwCv['_world_light_dir'][0])
  1348. + (glwCv['_world_light_dir'][2]
  1349. * glwCv['_world_light_dir'][2])
  1350. )
  1351. glwCv['_world_light_dir_eye_space'] = (
  1352. light_r * math.cos(light_theta),
  1353. glwCv['_world_light_dir_eye_space'][1],
  1354. light_r * math.sin(light_theta)
  1355. )
  1356. self._previous_camera_rotate_y_angle = \
  1357. self.camera_glop._r_ins_y.angle
  1358. self._previous_world_light_dir = (
  1359. glwCv['_world_light_dir'][0],
  1360. glwCv['_world_light_dir'][1],
  1361. glwCv['_world_light_dir'][2]
  1362. )
  1363. # pstep(debug_dict, pre="m_glop " + m_glop.name)
  1364. self._delay_is_available_enable = True
  1365. self.update_view_visual_debug()
  1366. # end update
Advertisement
Add Comment
Please, Sign In to add comment