GE Lua Documentation

Press F to search!

square

Definition


-- @/lua/common/mathlib.lua:1155

function square(a)
  return a * a
end

Callers

@/gameplay/missionTypes/evade/customNodes/scatterTrafficAwayNode.lua
    if v.isAi then
      if (self.pinIn.inverted.value and v.pos:squaredDistance(vec3(self.pinIn.pos.value)) > square(self.pinIn.radius.value))
      or (not self.pinIn.inverted.value and v.pos:squaredDistance(vec3(self.pinIn.pos.value)) <= square(self.pinIn.radius.value)) then
      if (self.pinIn.inverted.value and v.pos:squaredDistance(vec3(self.pinIn.pos.value)) > square(self.pinIn.radius.value))
      or (not self.pinIn.inverted.value and v.pos:squaredDistance(vec3(self.pinIn.pos.value)) <= square(self.pinIn.radius.value)) then
        gameplay_traffic.forceTeleport(id)
@/lua/vehicle/hydros.lua
      if lockForce >= 0 then
        lockForce = lockForce - min(lockForce, square(softlockDamping * max(0, abs(prevWheelPos) - absWheelPos) / physicsDt))
      end
    if jerkForceZ < jerkMinZ then jerkForceZ = 0 end
    local jerkForce = sqrt(square(jerkForceX) + square(jerkForceY) + square(jerkForceZ))
    if jerkForceZ < jerkMinZ then jerkForceZ = 0 end
    local jerkForce = sqrt(square(jerkForceX) + square(jerkForceY) + square(jerkForceZ))
    if jerkForceZ < jerkMinZ then jerkForceZ = 0 end
    local jerkForce = sqrt(square(jerkForceX) + square(jerkForceY) + square(jerkForceZ))
@/lua/vehicle/mapmgr.lua
  local xnormC = min(max((abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30), 0), 1)
  return square(asx - abx*xnormC) + square(asy - aby*xnormC) + wZ * square(asz - abz*xnormC)
end
  local xnormC = min(max((abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30), 0), 1)
  return square(asx - abx*xnormC) + square(asy - aby*xnormC) + wZ * square(asz - abz*xnormC)
end
  local xnormC = min(max((abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30), 0), 1)
  return square(asx - abx*xnormC) + square(asy - aby*xnormC) + wZ * square(asz - abz*xnormC)
end

    if curDist <= square(math.max(nodeRadius[n1id], nodeRadius[n2id])) then
      local xnorm = pos:xnormOnLine(nodePositions[n1id], nodePositions[n2id])
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
@/lua/common/jbeam/sections/wheels.lua
  --   wheel._surface = math.pi * (2 * (wheel.tireWidth * wheel.radius + wheel.hubWidth * wheel.hubRadius) +
  --     (wheel.radius + wheel.hubRadius) * math.sqrt(square(wheel.radius - wheel.hubRadius) + square(wheel.tireWidth - wheel.hubRadius)))
  -- end
  --   wheel._surface = math.pi * (2 * (wheel.tireWidth * wheel.radius + wheel.hubWidth * wheel.hubRadius) +
  --     (wheel.radius + wheel.hubRadius) * math.sqrt(square(wheel.radius - wheel.hubRadius) + square(wheel.tireWidth - wheel.hubRadius)))
  -- end
@/lua/ge/extensions/core/cameraModes/driver.lua
  -- Lock pitch to horizon
  local flatFwdLen = math.sqrt(square(carFwd.x) + square(carFwd.y))
  local carPitch = math.atan2(carFwd.z, flatFwdLen > 0 and flatFwdLen or 1e-12)
  -- Lock pitch to horizon
  local flatFwdLen = math.sqrt(square(carFwd.x) + square(carFwd.y))
  local carPitch = math.atan2(carFwd.z, flatFwdLen > 0 and flatFwdLen or 1e-12)
@/lua/ge/extensions/core/groundMarkers.lua
  local linearAlpha = min(dist, max(0, pos - start)) / dist
  return 0.5-square(square(1-linearAlpha)) -- increase opacity much sooner than a linear ramp
end
  local linearAlpha = min(dist, max(0, pos - start)) / dist
  return 0.5-square(square(1-linearAlpha)) -- increase opacity much sooner than a linear ramp
end
    -- enable this line for "quicker" blending
    --M.decalPool[idx].color.a = 1-square(1-M.decalPool[idx].color.a)
    idx = idx + 1
@/lua/ge/extensions/flowgraph/nodes/util/randomColor.lua
  if self.pinIn.cuteColor.value then
    local r, g, b = HSVtoRGB(math.random(), lerp(1, 0.7, square(math.random())), lerp(1, 0.7, square(math.random())))
    self.pinOut.color.value = {r, g, b, a}
  if self.pinIn.cuteColor.value then
    local r, g, b = HSVtoRGB(math.random(), lerp(1, 0.7, square(math.random())), lerp(1, 0.7, square(math.random())))
    self.pinOut.color.value = {r, g, b, a}
@/lua/ge/extensions/core/hotlapping.lua
        local sqDist = node.pos:squaredDistance(getPlayerVehicle(0):getPosition())
        if sqDist <= square(node.radius) then
          M.start()
@/lua/ge/extensions/scenario/busdriver.lua
    if v.smoothness.fill < 0.55 then v.smoothness.fill = 0 end
    result.smoothness.fill = 100 - 100*square(v.smoothness.fill)
    result.smoothness.mark = 100 - 100*square(v.smoothness.mark)
    result.smoothness.fill = 100 - 100*square(v.smoothness.fill)
    result.smoothness.mark = 100 - 100*square(v.smoothness.mark)
    result.smoothness.total= result.smoothness.total- 100*square(v.smoothness.fill) / nStops
    result.smoothness.mark = 100 - 100*square(v.smoothness.mark)
    result.smoothness.total= result.smoothness.total- 100*square(v.smoothness.fill) / nStops
@/lua/ge/extensions/editor/gen/world.lua
			local d = (ccenter - core_camera.getPosition()):length()
			local speed = 100*square(1/(1+1/d))
			core_camera.setSpeed(speed)
@/lua/vehicle/ai.lua
      -- abs
      brakeABSCoef = min(1, 1.5 * square(square(square(max(0, absegoSpeed - totalSlip) / absegoSpeed))))
      -- abs
      brakeABSCoef = min(1, 1.5 * square(square(square(max(0, absegoSpeed - totalSlip) / absegoSpeed))))
      -- abs
      brakeABSCoef = min(1, 1.5 * square(square(square(max(0, absegoSpeed - totalSlip) / absegoSpeed))))

    local aggSq = square(aggression + max(0, -(ego.dirVec:dot(gravityDir))))
    local rate = max(throttleSmoother[throttleSmoother:value() < throttle], 10 * aggSq * aggSq)
          if ego.pos:squaredDistance(linePointFromXnorm(p1Pos, plan[i+2].pos, nextXnorm)) <
              square(ego.width + lerp(p1Radius, plan[i+2].radiusOrig, min(1, nextXnorm))) then
            egoXnormOnSeg = nextXnorm
      local nid = currentRoute.path[plan[seg].pathidx]
      if seg < plan.planCount - 1 and tableSize(mapData.graph[nid]) > 2 and plan[seg].pos:squaredDistance(mapData.positions[nid]) <= square(mapData.radius[nid]) then
        dist = dist + 20

  return 2 * sqrt((1 - cosSq) / max(1e-30, square(v1x + v2x) + square(v1y + v2y) + square(v1z + v2z))) -- the denominator is v1:squaredLength(-v2)
end

  return 2 * sqrt((1 - cosSq) / max(1e-30, square(v1x + v2x) + square(v1y + v2y) + square(v1z + v2z))) -- the denominator is v1:squaredLength(-v2)
end

  return 2 * sqrt((1 - cosSq) / max(1e-30, square(v1x + v2x) + square(v1y + v2y) + square(v1z + v2z))) -- the denominator is v1:squaredLength(-v2)
end
  if ay_used < ay_max_tyre then
    return ax_max_tyre * sqrt(1 - square(ay_used/ay_max_tyre))
  else
  -- The last node speed value was not calculated from the limiting turn speed (due to absence of curvature value), so square it.
  plan[plan.planCount].speed = square(plan[plan.planCount].speed)
    local lanew = (plan1.rangeRight - plan1.rangeLeft)/plan1.rangeLaneCount
    if plan1.rangeLaneCount > 1 and ego.dirVec:dot(vdirVec) > 0.7 and ego2v < square((1.2 * ego.length + 1.2*v.length)) and (xnormV > plan1.rangeLeft and xnormV < plan1.rangeRight) and (not (xnormV > (plan1.rangeLeft + lanew*plan1.rangeBestLane) and xnormV < (plan1.rangeLeft + lanew*(plan1.rangeBestLane+1)))) then
      if draw then obj.debugDrawProxy:drawSphere(2, vPfront, color(0,0,0,160)) end
  --  ego.race.d = linearScale(dv, 0, 20, 0.5 * ego.length, 2 * ego.length)
  --  --ego.race.d = (square(ego.speed) - square(plan.trafficMinProjSpeed))/(min(aggression, ego.staticFrictionCoef) * 2 * g)
  --  ego.race.d = linearScale(dv, 0, 20, 0.5 * ego.length, 2 * ego.length)
  --  --ego.race.d = (square(ego.speed) - square(plan.trafficMinProjSpeed))/(min(aggression, ego.staticFrictionCoef) * 2 * g)

  --  local breaking_dist = max(0, (square(ego.speed) - square(plan.trafficMinProjSpeed))/(min(aggression, ego.staticFrictionCoef) * 2 * g))
  --  local safety_margin = plan.distances - breaking_dist

  --  local breaking_dist = max(0, (square(ego.speed) - square(plan.trafficMinProjSpeed))/(min(aggression, ego.staticFrictionCoef) * 2 * g))
  --  local safety_margin = plan.distances - breaking_dist
      local v_rel = dV:dot(nvec)   -- lateral relative speed between ego vehicle and v-vehicle
      local a = math.exp(-square(dS / egoLength)) -- Intensity factor
      a = a > 0.05 and a or 0
    local r = 1 / (abs(plan[i].curvature) + 1e-100)
    plan[i-1].fE = max(plan[i-1].fE, r - sqrt(max(0, r * r - square(0.5 * plan[i-1].length))))
    plan[i].fE = r - sqrt(max(0, r * r - square(0.5 * plan[i].length)))
    plan[i-1].fE = max(plan[i-1].fE, r - sqrt(max(0, r * r - square(0.5 * plan[i-1].length))))
    plan[i].fE = r - sqrt(max(0, r * r - square(0.5 * plan[i].length)))
  end
    if distOnPlan < 20 then
      plan[i].rfe = max(plan[i].rfe, 1 - sqrt(max(0, 1 - square(0.5 * plan[i].length * plan[i+1].curvature))))
    end
      local segLenSq = plan[i].posOrig:squaredDistance(plan[i+1].posOrig)
      if segLenSq > square(2 * radiusOrig + n1.radiusOrig + n2.radiusOrig) then
        -- calculate normal from the direction vector of edge (i, i+1)
    if distOnPlan < 20 then
      plan[i+1].rfe = 1 - sqrt(max(0, 1 - square(0.5 * plan[i+1].length * plan[i+1].curvature)))
    end
        local rad = lerp(rad2, rad1, xnorm)
        if xnorm >= 0 and xnorm <= 1 and sqDist <= square(2 * rad) then
          posOrig = linePointFromXnorm(pos2, pos1, xnorm)
      local lastPlanIdx = 2
      local targetDist = square(ego.speed) / (2 * g * aggression) + max(30, ego.speed * 3) -- longer adjustment at higher speeds
      local tmpVec = vec3()
    -- consider inclination
    gT:setSub2(n2.pos, n1.pos); gT:setScaled(gravityDir:dot(gT) / max(square(n1.length), 1e-30)) -- gravity vec parallel to road segment: positive when downhill
    local gN = gravityDir:distance(gT) -- gravity component normal to road segment
              if side < 0 then -- v-vehicle is on our left side
                dispLeft = max(dispLeft, square(clamp(0.1 / TTC, 0, 1)))
              elseif side > 0 then -- v-vehicle is on our right side  --(and (xnormF < 0.5 or v.vel:dot(ego.dirVec) > ego.speed))
              elseif side > 0 then -- v-vehicle is on our right side  --(and (xnormF < 0.5 or v.vel:dot(ego.dirVec) > ego.speed))
                dispRight = max(dispRight, square(clamp(0.1 / TTC, 0, 1)))
              end
      local lastPlanIdx = 2
      local targetDist = square(ego.speed) / (2 * g * aggression) + max(opt.racing and 100 or 30, ego.speed * 3) -- longer adjustment at higher speeds
          if v.vel:length() < ego.speed and (v.noproj or opt.racing) then
            velDisp = velDisp * min(1,square(square(square(max(0,arrivalT/4)))))
          end
          if v.vel:length() < ego.speed and (v.noproj or opt.racing) then
            velDisp = velDisp * min(1,square(square(square(max(0,arrivalT/4)))))
          end
          if v.vel:length() < ego.speed and (v.noproj or opt.racing) then
            velDisp = velDisp * min(1,square(square(square(max(0,arrivalT/4)))))
          end

        if minSqDist < square((ego.width + limWidth) * 0.8) then
          local velProjOnSeg = max(0, v.vel:dot(nDir))
                  if v.sideDir == sign(distY) then
                    local forceCoef = sign(distY)*max(0, ((n1i.radiusOrig) - abs(distY))*math.exp(-0.001*square(Deltax)))*(1*parameters.awarenessForceCoef*dt)
                    forceCoef = forceCoef*max(factor1, factor2)*trafficStates.side.side

            if minSqDist < square((ego.width + limWidth) * 0.51)  then
              -- obj.debugDrawProxy:drawSphere(0.25, v.posFront, color(0,0,255,255))

            if i == 2 and minSqDist < square((ego.width + limWidth) * 0.6) and ego2PlDir > 0 and v.vel:dot(ego.rightVec) * ego2PlVec:dot(ego.rightVec) < 0 then
              n1.trafficSqVel = max(0, n1.trafficSqVel - abs(1 - v.vel:dot(ego.dirVec)) * (v.vel:length()))
            n.laneLimRight = max(n.laneLimLeft + ego.width, min(n.laneLimRight, n.lateralXnorm + laneHalfWidth))
            forces[i]:setAdd(planDist * sideForceCoeff * square(min(1, 0.25 * abs(n.lateralXnorm - n.laneLimLeft))) * n.normal)
          else
            n.laneLimLeft = min(n.laneLimRight - ego.width, max(n.laneLimLeft, n.lateralXnorm - laneHalfWidth))
            forces[i]:setAdd(planDist * sideForceCoeff * square(min(1, 0.25 * abs(n.laneLimRight - n.lateralXnorm))) * n.normal)
          end
          if side < 0 then
            forces[i]:setAdd(planDist * sideForceCoeff * square(min(1, 0.25 * abs(n.lateralXnorm - n.laneLimLeft))) * n.normal)
          else
          else
            forces[i]:setAdd(planDist * sideForceCoeff * square(min(1, 0.25 * abs(n.laneLimRight - n.lateralXnorm))) * n.normal)
          end
      -- consider inclination
      gT:setSub2(n2.pos, n1.pos); gT:setScaled(gravityDir:dot(gT) / max(square(n1.length), 1e-30)) -- gravity vec parallel to road segment: positive when downhill
      local gN = gravityDir:distance(gT) -- gravity component normal to road segment
      -- consider inclination
      gT:setSub2(n2.pos, n1.pos); gT:setScaled(gravityDir:dot(gT) / max(square(n1.length), 1e-30)) -- gravity vec parallel to road segment: positive when downhill
      local gN = gravityDir:distance(gT) -- gravity component normal to road segment
        -- https://physics.stackexchange.com/questions/312569/non-uniform-circular-motion-velocity-optimization
        n1SpeedSq = min(n1.trafficSqVel, turnSpeedSq * sin(min(asin(min(1, square(n2.speed) / turnSpeedSq)) + 2 * curvature * n1.length, pi * 0.5)))
      end
        else -- speed limit imposed by other traffic vehicles and speed limit imposed by trajectory geometry (curvature and path length)
          local n1LegalSpeedSq = min(n1.trafficSqVel, turnSpeedSq * sin(min(asin(min(1, square(n2.legalSpeed) / turnSpeedSq)) + 2 * curvature * n1.length, pi * 0.5)))
          if n1.roadSpeedLimit then

  if internalState.chaseData.playerStoppedTimer > 5 and egoPlDist < max(nearDist, square(ego.speed) / (2 * g * aggression)) then -- within braking distance to player
    internalState.chaseData.playerState = 'stopped'
    if M.mode == 'chase' then
      local brakeDist = square(ego.speed) / (2 * g * aggression)
      local relSpeed = playerVel:dot(ego.dirVec)
  if pullOver and not trafficStates.action.forcedStop and ego.speed >= 3 then
    local brakeDist = square(ego.speed) / (2 * g * aggression)
    local dist = max(10, brakeDist)
    local stopSeg = math.huge
    local brakeDist = square(ego.speed) / (2 * g * ego.staticFrictionCoef * min(1, aggression * 1.3))
    local distSq = ego.pos:squaredDistance(tSi.pos)
    if tSi.pos:dot(tSi.dir) + 4 * tSi.dir:dot(tSi.dir) >= ego.pos:dot(tSi.dir)  then -- vehicle position is at the stop pos (with extra distance, to be safe)
      if tSi.action == 3 or tSi.action == 2 or (tSi.action == 1 and (square(brakeDist) < distSq or tSi.commitStopOnYellow)) then -- red light or other stop condition
        local bestDist = 100
                if not isVehicleStopped(v) and v.dirVec:dot(vPosF - (ego.pos + distToJcenter * ego.dirVec)) < 0 then
                  checkDirRad = v.dirVec:dot(tSi.dir) < 0.707 and egoCenterPos:squaredDistance(vPosF) < square(max(min(60, max(40, v.vel:squaredLength() / (g * ego.staticFrictionCoef))), v.vel:length()*4))
                end
    plan.stopSeg = stopSeg
    if parameters.enableElectrics and tSi.turnNode and ego.pos:squaredDistance(mapData.positions[tSi.turnNode]) < square(max(50, brakeDist * 1.2)) then -- approaching intersection
      if tSi.turn < 0 and electrics.values.turnsignal >= 0 then
            local kcurvature = 2 * abs(d:dot(n)) * dSqLengthInv
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            local kcurvature = 2 * abs(d:dot(n)) * dSqLengthInv
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            if acc_check then goto continue end
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            if acc_check then goto continue end
            local kcurvature = 2 * abs(d:dot(n)) * dSqLengthInv
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            local kcurvature = 2 * abs(d:dot(n)) * dSqLengthInv
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            if acc_check then goto continue end
            local axSq = square(0.5 * max(egoSqspeed - square(kplan[kplan.targetSeg].speed), 0)) * dSqLengthInv
            local acc_check = square(mainPlan[1].acc_max) - axSq <= square(egoSqspeed * kcurvature)
            if acc_check then goto continue end
            local targetError = (push3(mainPlan.targetPos) - targetPos):dot(mainPlan[mainPlan.targetSeg].normal)
            if square(targetError) < 0.8 or (plan_index == 1 and targetError < 0) or (plan_index == 2 and targetError > 0) then
              currentRoute.reAltplan = true
      planAhead(currentRoute)
      local targetSpeed = max(0, ego.speed - sqrt(max(0, square(ego.staticFrictionCoef * g) - square(sensors.gx2))) * dt) -- TODO: check this calculation, i don't think it does what you think it does
      currentRoute.plan.targetSpeed = min(currentRoute.plan.targetSpeed, targetSpeed)
      planAhead(currentRoute)
      local targetSpeed = max(0, ego.speed - sqrt(max(0, square(ego.staticFrictionCoef * g) - square(sensors.gx2))) * dt) -- TODO: check this calculation, i don't think it does what you think it does
      currentRoute.plan.targetSpeed = min(currentRoute.plan.targetSpeed, targetSpeed)
      -- check if deceleration without braking is larger or equal to the desired deceleration
      if sensors.gy2 >= (square(plan[1].speed) - square(plan[2].speed)) / (2 * plan[1].length) then
        brake = 0
      -- check if deceleration without braking is larger or equal to the desired deceleration
      if sensors.gy2 >= (square(plan[1].speed) - square(plan[2].speed)) / (2 * plan[1].length) then
        brake = 0
@/lua/ge/extensions/gameplay/traffic/roles/police.lua
    local distSq = self.veh.pos:squaredDistance(targetVeh.pos)
    local brakeDistSq = square(self.veh:getBrakingDistance(self.veh.speed, 1) + 20)
    local targetVisible = self.validTargets[self.targetId or 0] and self.validTargets[self.targetId].visible
@/lua/ge/extensions/gameplay/rally/loop/rallyLoopManager.lua
        local distanceSq = vehPos:squaredDistance(skipEventPos)
        local distanceThresholdSq = square(self.skipParams.distanceMeters)
        local distanceThresholdSqMin = square(self.skipParams.distanceMetersMin)
        local distanceThresholdSq = square(self.skipParams.distanceMeters)
        local distanceThresholdSqMin = square(self.skipParams.distanceMetersMin)
        local velocity = veh:getVelocity():length()
@/lua/ge/extensions/gameplay/traffic/vehicle.lua

  return square(speed or self.speed) / (2 * (accel or self.role.driver.aggression) * abs(gravity))
end

        if not isCurrentCollision and dist > square(collision.vehDist + 1) then
          collision.inArea = false
              self.role:setAction('pullOver')
            elseif not isCurrentCollision and self.role.flags.pullOver and dist > square(collision.vehDist + 3) then -- restarts AI after a small distance (greater than jump distance)
              self.role:resetAction()
        tempPos:setAdd2(mapData.pos, tempPos)
        if self.pos:squaredDistance(tempPos) < square(self.respawn.innerRadius) then -- prevents respawning if too close
          valid = false
    tempPos:setLerp(p1, p2, xnorm)
    self.tracking.isOnRoad = self.pos:squaredDistance(tempPos) <= square(radius + 1) -- small buffer at edge of road
        local center = vec3(be:getObjectOOBBCenterXYZ(id)) -- for accuracy
        validCollision = self.pos:z0():squaredDistance(center:z0()) < square(veh.width * 0.6) or coll.count >= 3 -- jumping on car, or multiple hits
      end
@/lua/ge/extensions/gameplay/traffic/trafficUtils.lua

  if pos:squaredDistance(origPos) < square(minDist) then
    return false
        local gravity = core_environment.getGravity()
        relSpeed = square(relSpeed * relSpeedCoef) / (2 * math.max(0.1, math.abs(gravity)) * sign2(gravity) * -1)
      end
      local radius = veh:isPlayerControlled() and minDist or minVehDist
      if pos:squaredDistance(tempPos) < square(math.max(radius, relSpeed)) then
        return false
@/lua/ge/extensions/flowgraph/nodes/vehicle/ai/scriptAI/pathStored.lua
  local camPos = core_camera.getPosition()
  local cutoffPointSq = square(clamp(focusPos:distance(camPos), 100, 200))
@/lua/ge/extensions/core/audioRibbon.lua
-- Module constants.
local nearFarLimitSq = square(500.0) -- The maximum distance for near-field dynamic SFX emitters
local radiusLength = 0.5 -- The length of the radius multiplier.
@/lua/ge/extensions/gameplay/traffic/roles/standard.lua

    local squareRandom = square(random())
    self.driver.damageThreshold = max(self.veh.damageLimits[1], squareRandom * 1000) -- minimum damage that triggers damage action
  if self.flags.honkHornDelay and random() >= 0.9 then
    self.veh:honkHorn(max(0.25, square(random()) * 1.5))
    self.flags.honkHornDelay = nil
@/lua/ge/extensions/editor/gen/decal.lua
        local r = (rd.aw[1]/2 + margin + 0.1)*2/math.sqrt(2) -- scan stamp size
        local step = 2*math.sqrt(square(r) - square(rd.aw[1]/2 + margin)) -- distance between stamps
        local cext = 1 -- how far edges to check for toPath
        local r = (rd.aw[1]/2 + margin + 0.1)*2/math.sqrt(2) -- scan stamp size
        local step = 2*math.sqrt(square(r) - square(rd.aw[1]/2 + margin)) -- distance between stamps
        local cext = 1 -- how far edges to check for toPath
@/lua/ge/extensions/gameplay/police.lua
        -- visible and within arrest distance
        if bestPoliceId and bestDist < square(arrestRadius) then
          if veh.speed <= 2.5 and policeVehs[bestPoliceId].speed <= 2.5 and bestDist < square(arrestRadius) then
        if bestPoliceId and bestDist < square(arrestRadius) then
          if veh.speed <= 2.5 and policeVehs[bestPoliceId].speed <= 2.5 and bestDist < square(arrestRadius) then
            pursuit.timers.arrest = min(vars.arrestTime, pursuit.timers.arrest + dtSim)

          if bestDist > square(evadeRadius) then
            pursuit.timers.evade = min(vars.evadeTime, pursuit.timers.evade + dtSim)
            pursuit.timers.evade = min(vars.evadeTime, pursuit.timers.evade + dtSim)
          elseif bestDist <= square(evadeRadius * 0.5) then
            pursuit.timers.evade = 0
@/lua/ge/extensions/gameplay/sites/location.lua

  local drawSqDist = square(editor.isEditorActive() and editor.getPreference("gizmos.visualization.visualizationDrawDistance") or 300)
  local camSqDist = self.pos:squaredDistance(core_camera.getPosition())
@/lua/vehicle/scriptai.lua
      -- abs
      brake = brake * square(max(0, absAiSpeed - totalSlip) / absAiSpeed)
@/lua/ge/extensions/freeroam/bigMapMarkers.lua
        elseif bmi.cluster and candidate.markerInfo.bigmapMarker.cluster then
          if bmi.pos:squaredDistance(candidate.markerInfo.bigmapMarker.pos) < square(settings.radius) then
            table.insert(cluster, candidate)
@/lua/common/kdtreepoint3d.lua
  local k = ceil((self.itemCount + 1) * 0.5) * 4 -- use median point for first best dist estimate
  local bestDist = square(items[k-3] - point[1]) + square(items[k-2] - point[2]) + square(items[k-1] - point[3]) -- best dist estimate
  local bestPointId = items[k]
  local k = ceil((self.itemCount + 1) * 0.5) * 4 -- use median point for first best dist estimate
  local bestDist = square(items[k-3] - point[1]) + square(items[k-2] - point[2]) + square(items[k-1] - point[3]) -- best dist estimate
  local bestPointId = items[k]
  local k = ceil((self.itemCount + 1) * 0.5) * 4 -- use median point for first best dist estimate
  local bestDist = square(items[k-3] - point[1]) + square(items[k-2] - point[2]) + square(items[k-1] - point[3]) -- best dist estimate
  local bestPointId = items[k]
    for i = tree[nodeIdx-2], tree[nodeIdx], 4 do
      local dist = square(items[i-3] - point[1]) + square(items[i-2] - point[2]) + square(items[i-1] - point[3])
      if dist < bestDist then
    for i = tree[nodeIdx-2], tree[nodeIdx], 4 do
      local dist = square(items[i-3] - point[1]) + square(items[i-2] - point[2]) + square(items[i-1] - point[3])
      if dist < bestDist then
    for i = tree[nodeIdx-2], tree[nodeIdx], 4 do
      local dist = square(items[i-3] - point[1]) + square(items[i-2] - point[2]) + square(items[i-1] - point[3])
      if dist < bestDist then
      local childIdx = tableRemove(stack)
      if square(tree[floor(childIdx*0.125)*4-1] - point[axis]) < bestDist then -- floor(childIdx * 0.125) * 4 is the idx of the parent of childIdx
        nodeIdx = childIdx
@/lua/ge/extensions/gameplay/sites/zone.lua
  if not isVisible then
    local drawSqDist = square(editor.isEditorActive() and editor.getPreference("gizmos.visualization.visualizationDrawDistance") or 500)
    for _, v in ipairs(self.vertices) do
@/lua/ge/extensions/flowgraph/nodes/vehicle/gForce.lua
  self.pinOut.gz.value = (values.accZSmooth - gravity) / gravity
  self.pinOut.gForce.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value) + square(self.pinOut.gz.value))
  self.pinOut.gForceZ0.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value))
  self.pinOut.gz.value = (values.accZSmooth - gravity) / gravity
  self.pinOut.gForce.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value) + square(self.pinOut.gz.value))
  self.pinOut.gForceZ0.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value))
  self.pinOut.gz.value = (values.accZSmooth - gravity) / gravity
  self.pinOut.gForce.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value) + square(self.pinOut.gz.value))
  self.pinOut.gForceZ0.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value))
  self.pinOut.gForce.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value) + square(self.pinOut.gz.value))
  self.pinOut.gForceZ0.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value))
end
  self.pinOut.gForce.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value) + square(self.pinOut.gz.value))
  self.pinOut.gForceZ0.value = math.sqrt(square(self.pinOut.gx.value) + square(self.pinOut.gy.value))
end
@/lua/ge/ge_utils.lua
  if math.random() <= commonPaintProb then -- if true, selects a color that is typically found in the real world (commonPaints)
    local n = square(math.random()) * 6 -- selects a common paint, with diminishing likelihood
    if n > 0.2 then -- arbitrary cutoff value for common paints (if lower, selects the assigned default paint of the vehicle)
@/lua/ge/extensions/gameplay/sites/parkingSpot.lua
  local alpha = drawMode == 'normal' and 0.4 or 1
  local textDrawDist = drawMode == 'highlight' and math.huge or square(drawDist)
  if drawMode ~= 'faded' and camSqDist <= textDrawDist then

  if camSqDist > square(drawDist) then return end

    if camSqDist <= square(drawDist * 0.333) then -- for performance reasons
      debugDrawer:drawTriSolid(

  if speed <= square(drivingSpeed) then
    bbCenter:set(be:getObjectOOBBCenterXYZ(vehId))

  if speed > square(parkingSpeed) then valid = false end
@/lua/ge/extensions/core/sounds.lua
        local isCameraInside = (core_camera and core_camera.isCameraInside(0, camPos)) or 0
        globalParams:setParameterValue("g_CamOnboard", square(square(insideModifier)) * isCameraInside) -- cockpit flag, used e.g. for driver camera
        globalParams:setParameterValue("c_CabinFilterReverbStrength", clamp(M.cabinFilterStrength, 0, 1)) -- cockpit flag, used e.g. for driver camera
        local isCameraInside = (core_camera and core_camera.isCameraInside(0, camPos)) or 0
        globalParams:setParameterValue("g_CamOnboard", square(square(insideModifier)) * isCameraInside) -- cockpit flag, used e.g. for driver camera
        globalParams:setParameterValue("c_CabinFilterReverbStrength", clamp(M.cabinFilterStrength, 0, 1)) -- cockpit flag, used e.g. for driver camera
@/lua/ge/extensions/editor/trafficSignalsEditor.lua
      if (internalName and obj:getInternalName() == internalName) or obj.shapeName == selectedObj.shapeName then
        if selectedObj:getPosition():squaredDistance(obj:getPosition()) <= square(radius) then
          -- strong assumption that the TSStatics were created with the same initial rotation
      for i, instance in ipairs(instances) do
        if mousePos:squaredDistance(instance.pos) <= square(cylinderRadius * 2) then
          selectInstance(i)
    local camDist = instance.pos:squaredDistance(core_camera.getPosition())
    if camDist <= square(editor.getPreference("gizmos.visualization.visualizationDrawDistance")) or selected.signal == i then
      instance:drawDebug(true, selected.signal == i, true, getCapColor(elements[instance.sequenceId == targetSequenceId and instance.controllerId or -1]), 5, 2)
@/lua/ge/extensions/gameplay/traffic.lua
        spawnPointDirVec:set(focus.dirVec)
        local addedDist = min(120, square(focus.dist * 0.15)) -- affects spawn point distance and deviation
        addedDist = addedDist + random() * auxiliaryData.dynamicSpawnDist -- distance ahead plus distance scattering

        local reverseProb = square(auxiliaryData.activeAmount) * 1e-3 -- reverse direction probability (scales with traffic amount)
        if focus.dist < 5 then reverseProb = 0.3 end -- player is stationary or slow (includes walking)
        local height = max(-1e6, be:getSurfaceHeightBelow(focus.pos))
        focus.dist = clamp(square(focus.pos.z - height) / 15, 20, 200) -- forced minimum distance of 20 m
      end
@/lua/ge/extensions/gameplay/race/race.lua

          if data.frontPos:squaredDistance(roadPos) > square(rad) then -- if front position is at the side edge of the road, test all corners
            data.isOnRoad = false
            for _, corner in ipairs(data.currentCorners) do
              if corner:squaredDistance(roadPos) <= square(rad) then
                data.isOnRoad = true
@/lua/ge/map.lua
          if (endNodesOnly and nodeDist < 0.01 and abs(n1.radius - mapNodes[n2id].radius) < 0.1)
            or (not endNodesOnly and nodeDist < square(max(n1.radius, mapNodes[n2id].radius))) then
            -- create edge between overlapping nodes (graph is one sided)
    local tempVec = (linePointFromXnorm(l2n1pos, l2n2pos, l1n1pos:xnormOnLine(l2n1pos, l2n2pos)) - l1n1pos):normalized() * (l2Prad + l1n1rad)
    if l1n1pos:squaredDistanceToLine(l2n1pos, l2n2pos) < tempVec:z0():squaredLength() then -- square(l2Prad + l1n1rad) -- Why z0?
      return edgeId, l2Xnorm
              local l2Prad = lerp(l2n1rad, l2n2rad, l2xn)
              if t1:squaredDistance(t2) < square(min(l1Prad, l2Prad) * 0.5) then
                junctionid = junctionid + 1
            local d2 = n.pos:squaredDistance(linePoint)
            if d2 < min(square(min(linePrad, n.radius)), d2Min) then -- TODO: do i need to keep the minimum? Why not keep all that safisfy the radius condition?
              d2Min, nodeMin, eIdMin, xMin = d2, nid, edgeId, xnorm
  --   local n2 = map.nodes[n2id]
  --   if not (n1.pos:squaredDistance(n2.pos) < square(min(n1.radius, n2.radius))) then
  --     print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! mergeNodesToLines Error 1 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')

        if maxj and maxd2 > square(map.nodes[path[maxj]].radius * 0.05) then
          nodesToKeep[maxj] = true

    if curDist <= square(math.max(mapNodes[n1id].radius, mapNodes[n2id].radius)) then
      local xnorm = pos:xnormOnLine(mapNodes[n1id].pos, mapNodes[n2id].pos)
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
              tmpVec:setScaled(max(0, 1 - max(nodeRadius[n1id], nodeRadius[n2id]) / (tmpVec:length() + 1e-30)))
              costs[key] = square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
              j = j + 1
@/lua/ge/extensions/flowgraph/nodes/vehicle/ai/followWaypoints.lua
    local vehPos = veh:getPosition()
    if not self.lapFlag and vehPos:squaredDistance(mapNodes[self.pinOut.finalWp.value].pos) < square(mapNodes[self.pinOut.finalWp.value].radius) then
      -- vehicle is within radius of final waypoint
@/lua/ge/extensions/core/vehicleActivePooling.lua
    if obj then
      if state == 1 and vehPos:squaredDistance(pos) > square(dist + 10) then -- 10m buffer
        obj:setActive(0)
      end
      if state == 0 and vehPos:squaredDistance(pos) <= square(dist) then
        obj:setActive(1)
@/lua/ge/extensions/flowgraph/nodes/vehicle/ai/directlyTo.lua
        local distance = origin:squaredDistance(target)
        if distance < square(self.data.minDistance) then
          self:endAI()
@/lua/ge/extensions/gameplay/util/crashDetection.lua

    local accel = abs(point.smootherAcc:getUncapped(sqrt(square(tempVecCurrAccel.x) + square(tempVecCurrAccel.y) + square(tempVecCurrAccel.z)), dtSim))

    local accel = abs(point.smootherAcc:getUncapped(sqrt(square(tempVecCurrAccel.x) + square(tempVecCurrAccel.y) + square(tempVecCurrAccel.z)), dtSim))

    local accel = abs(point.smootherAcc:getUncapped(sqrt(square(tempVecCurrAccel.x) + square(tempVecCurrAccel.y) + square(tempVecCurrAccel.z)), dtSim))
@/lua/common/graphpath.lua
      nodeToTargetVec:setSub2(target, p1)
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      if pathCost < targetMinCost then
      nodeToTargetVec:setSub2(target, p1)
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      if pathCost < targetMinCost then
      nodeToTargetVec:setSub2(target, p1)
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      if pathCost < targetMinCost then
      nodeToTargetVec:setSub2(target, p1)
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      if pathCost < targetMinCost then
                      (edgeCost or data.len * dirCoeff[data.oneWay and data.inNode == outNode] * drivCoeff[data.drivability > cutOffDrivability]) * xnorm +
                      square(square(max(0, math.sqrt(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z)) - (rnode + (rchild - rnode) * xnorm))))
            if pathCost < targetMinCost then
                      (edgeCost or data.len * dirCoeff[data.oneWay and data.inNode == outNode] * drivCoeff[data.drivability > cutOffDrivability]) * xnorm +
                      square(square(max(0, math.sqrt(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z)) - (rnode + (rchild - rnode) * xnorm))))
            if pathCost < targetMinCost then
                      (edgeCost or data.len * dirCoeff[data.oneWay and data.inNode == outNode] * drivCoeff[data.drivability > cutOffDrivability]) * xnorm +
                      square(square(max(0, math.sqrt(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z)) - (rnode + (rchild - rnode) * xnorm))))
            if pathCost < targetMinCost then
                      (edgeCost or data.len * dirCoeff[data.oneWay and data.inNode == outNode] * drivCoeff[data.drivability > cutOffDrivability]) * xnorm +
                      square(square(max(0, math.sqrt(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z)) - (rnode + (rchild - rnode) * xnorm))))
            if pathCost < targetMinCost then
                      (edgeCost or data.len * dirCoeff[data.oneWay and data.inNode == outNode] * drivCoeff[data.drivability > cutOffDrivability]) * xnorm +
                      square(square(max(0, math.sqrt(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z)) - (rnode + (rchild - rnode) * xnorm))))
            if pathCost < targetMinCost then
  local road = table.new(0, 32) -- initialize shortest paths linked list
  local targetMinCost = square(square(sourcePos.x-targetPos.x) + square(sourcePos.y-targetPos.y) + square(wZ * (sourcePos.z-targetPos.z))) -- upper bound estimate for the path cost
  local targetMinCostLink = nil
  local road = table.new(0, 32) -- initialize shortest paths linked list
  local targetMinCost = square(square(sourcePos.x-targetPos.x) + square(sourcePos.y-targetPos.y) + square(wZ * (sourcePos.z-targetPos.z))) -- upper bound estimate for the path cost
  local targetMinCostLink = nil
  local road = table.new(0, 32) -- initialize shortest paths linked list
  local targetMinCost = square(square(sourcePos.x-targetPos.x) + square(sourcePos.y-targetPos.y) + square(wZ * (sourcePos.z-targetPos.z))) -- upper bound estimate for the path cost
  local targetMinCostLink = nil
  local road = table.new(0, 32) -- initialize shortest paths linked list
  local targetMinCost = square(square(sourcePos.x-targetPos.x) + square(sourcePos.y-targetPos.y) + square(wZ * (sourcePos.z-targetPos.z))) -- upper bound estimate for the path cost
  local targetMinCostLink = nil
      -- Cost of path if we were to go straight from this node to the target position
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      -- if pathCost is lower than the current upper bound estimate insert the targetPos in que with this cost
      -- Cost of path if we were to go straight from this node to the target position
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      -- if pathCost is lower than the current upper bound estimate insert the targetPos in que with this cost
      -- Cost of path if we were to go straight from this node to the target position
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      -- if pathCost is lower than the current upper bound estimate insert the targetPos in que with this cost
      -- Cost of path if we were to go straight from this node to the target position
      local pathCost = cost + square(square(nodeToTargetVec.x) + square(nodeToTargetVec.y) + square(wZ * nodeToTargetVec.z))
      -- if pathCost is lower than the current upper bound estimate insert the targetPos in que with this cost
                      (edgeCost or edgeData.len * dirCoeff[edgeData.oneWay and edgeData.inNode == child] * drivCoeff[edgeData.drivability > cutOffDrivability]) * xnorm +
                      square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
            if pathCost < targetMinCost then
                      (edgeCost or edgeData.len * dirCoeff[edgeData.oneWay and edgeData.inNode == child] * drivCoeff[edgeData.drivability > cutOffDrivability]) * xnorm +
                      square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
            if pathCost < targetMinCost then
                      (edgeCost or edgeData.len * dirCoeff[edgeData.oneWay and edgeData.inNode == child] * drivCoeff[edgeData.drivability > cutOffDrivability]) * xnorm +
                      square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
            if pathCost < targetMinCost then
                      (edgeCost or edgeData.len * dirCoeff[edgeData.oneWay and edgeData.inNode == child] * drivCoeff[edgeData.drivability > cutOffDrivability]) * xnorm +
                      square(square(tmpVec.x) + square(tmpVec.y) + square(wZ * tmpVec.z))
            if pathCost < targetMinCost then

  pathLenLim = square(pathLenLim)
            local cDirCoef = 0.5 * max(0, 1 + nextSegDir:dot(curSegDir))
            local t = square(square(min(1, graph[node][child].drivability / inDrivability))) * square(cDirCoef)
            local totalLanes, numOfLanesInDir = self:numOfEdgeLanes(node, child)
            local cDirCoef = 0.5 * max(0, 1 + nextSegDir:dot(curSegDir))
            local t = square(square(min(1, graph[node][child].drivability / inDrivability))) * square(cDirCoef)
            local totalLanes, numOfLanesInDir = self:numOfEdgeLanes(node, child)
            local cDirCoef = 0.5 * max(0, 1 + nextSegDir:dot(curSegDir))
            local t = square(square(min(1, graph[node][child].drivability / inDrivability))) * square(cDirCoef)
            local totalLanes, numOfLanesInDir = self:numOfEdgeLanes(node, child)

  --pathLenLim = square(pathLenLim * (1 + (math.random() - 0.5) * 0.4))
  pathLenLim = square(pathLenLim)
  --pathLenLim = square(pathLenLim * (1 + (math.random() - 0.5) * 0.4))
  pathLenLim = square(pathLenLim)
        nextSegDir:setSub2(positions[child], positions[node]); nextSegDir.z = 0; nextSegDir:normalize()
        local t = square(min(1, graph[node][child].drivability / inDrivability)) * square(0.5 * max(0, 1 + nextSegDir:dot(curSegDir)))
        local outFwdFlow, outBackFlow = self:getFlows(node, child)
        nextSegDir:setSub2(positions[child], positions[node]); nextSegDir.z = 0; nextSegDir:normalize()
        local t = square(min(1, graph[node][child].drivability / inDrivability)) * square(0.5 * max(0, 1 + nextSegDir:dot(curSegDir)))
        local outFwdFlow, outBackFlow = self:getFlows(node, child)
              nextSegDir:setSub2(positions[child], nodePos); nextSegDir.z = 0; nextSegDir:normalize()
              local t = square(min(1, graph[node][child].drivability / inDrivability)) * square(0.5 * max(0, 1 + nextSegDir:dot(curSegDir)))
              local outFwdFlow, outBackFlow = self:getFlows(node, child)
              nextSegDir:setSub2(positions[child], nodePos); nextSegDir.z = 0; nextSegDir:normalize()
              local t = square(min(1, graph[node][child].drivability / inDrivability)) * square(0.5 * max(0, 1 + nextSegDir:dot(curSegDir)))
              local outFwdFlow, outBackFlow = self:getFlows(node, child)
              nextSegDir:setSub2(positions[child], nodePos); nextSegDir.z = 0; nextSegDir:normalize()
              local t = square(min(1, graph[node][child].drivability / inDrivability)) * square(0.5 * max(0, 1 + nextSegDir:dot(curSegDir)))
              local outFwdFlow, outBackFlow = self:getFlows(node, child)
              nextSegDir:setSub2(positions[child], nodePos); nextSegDir.z = 0; nextSegDir:normalize()
              local t = square(min(1, graph[node][child].drivability / inDrivability)) * square(0.5 * max(0, 1 + nextSegDir:dot(curSegDir)))
              local outFwdFlow, outBackFlow = self:getFlows(node, child)
            local childCurrCost = minCost[child]
            local penalty = 1 + 10 * square(max(0, edgeDirVec:dot((positions[child] - nodePos):normalized()) - 0.2))
            local childNewCost = cost + penalty * data.len * dirCoeff[data.oneWay and data.inNode == child] * ((node == nodeAhead and child == nodeBehind) and 1e4 or 1)
      else
        tableInsert(choiceSet, {node, square(1/cost)})
        costSum = costSum + square(1/cost)
        tableInsert(choiceSet, {node, square(1/cost)})
        costSum = costSum + square(1/cost)
        if #choiceSet == 5 then
@/lua/vehicle/extensions/dynamicVehicleData.lua
  local distance60 = (endPosition - startingPosition60):length() * 3.28084
  local avgDeceleration = -(square(electrics.values.airspeed) - square(hundredKmh)) / (2 * distance100)
  local distance60 = (endPosition - startingPosition60):length() * 3.28084
  local avgDeceleration = -(square(electrics.values.airspeed) - square(hundredKmh)) / (2 * distance100)
@/lua/vehicle/input.lua
  local accel = obj:getStaticFrictionCoef() * getTotalDownforceFactor()
  local radius = square(vel) / accel
  return clamp(radius, 0, 100000)
  if a2 and diff > 0 then
    return a2 + b2 * diffabs + square(c2 * diffabs)
  else
  else
    return a1 + b1 * diffabs + square(c1 * diffabs)
  end
    local countersteer = oversteerMult * stabilizationMultiplier
    st = st + sign(countersteer) * max(0, 1 - square(st)) * min(1, abs(countersteer))
  end
          -- progressive (move faster after half-lock to guarantee full lock)
          ival = ival * relation + sign(ival) * square(2 * max(0.5, abs(ival)) - 1) * max(0, 1 - relation) -- ival = linear + nonlinear
        elseif not lockTypeWarned then
@/lua/ge/extensions/core/multiSpawn.lua
      else
        factor = min(1, square((100 - max(0, params.maxYear - config.yearMax)) / 100))
      end
@/lua/common/mathlib.lua
  local xnorm = (abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30) -- ab:dot(a-self)/ab:dot(ab)
  return square(asx - abx*xnorm) + square(asy - aby*xnorm) + square(asz - abz*xnorm) -- (a-self):squaredDistance(ab * xnorm)
end
  local xnorm = (abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30) -- ab:dot(a-self)/ab:dot(ab)
  return square(asx - abx*xnorm) + square(asy - aby*xnorm) + square(asz - abz*xnorm) -- (a-self):squaredDistance(ab * xnorm)
end
  local xnorm = (abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30) -- ab:dot(a-self)/ab:dot(ab)
  return square(asx - abx*xnorm) + square(asy - aby*xnorm) + square(asz - abz*xnorm) -- (a-self):squaredDistance(ab * xnorm)
end
  local xnormC = min(max((abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30), 0), 1) -- min(max(ab:dot(a-self)/ab:dot(ab), 0), 1)
  return square(asx - abx*xnormC) + square(asy - aby*xnormC) + square(asz - abz*xnormC) -- (a-self):squaredDistance(ab * xnormC)
end
  local xnormC = min(max((abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30), 0), 1) -- min(max(ab:dot(a-self)/ab:dot(ab), 0), 1)
  return square(asx - abx*xnormC) + square(asy - aby*xnormC) + square(asz - abz*xnormC) -- (a-self):squaredDistance(ab * xnormC)
end
  local xnormC = min(max((abx*asx + aby*asy + abz*asz) / (abx*abx + aby*aby + abz*abz + 1e-30), 0), 1) -- min(max(ab:dot(a-self)/ab:dot(ab), 0), 1)
  return square(asx - abx*xnormC) + square(asy - aby*xnormC) + square(asz - abz*xnormC) -- (a-self):squaredDistance(ab * xnormC)
end
  local xnormC = min(max(xnorm, 0), 1)
  return xnorm, square(asx - abx*xnormC) + square(asy - aby*xnormC) + square(asz - abz*xnormC)
end
  local xnormC = min(max(xnorm, 0), 1)
  return xnorm, square(asx - abx*xnormC) + square(asy - aby*xnormC) + square(asz - abz*xnormC)
end
  local xnormC = min(max(xnorm, 0), 1)
  return xnorm, square(asx - abx*xnormC) + square(asy - aby*xnormC) + square(asz - abz*xnormC)
end
  x = min(max(x, 0), 1)
  return square(x*x)*(35-x*(x*(x*20-70)+84))
end
  a, b, c = min(max(a/max(x1sql, 1e-30),-1),1), min(max(b/max(y1sql, 1e-30),-1),1), min(max(c/max(z1sql, 1e-30),-1),1)
  return square(a*x1.x+b*y1.x+c*z1.x-tmpv1.x) + square(a*x1.y+b*y1.y+c*z1.y-tmpv1.y) + square(a*x1.z+b*y1.z+c*z1.z-tmpv1.z)
end
  a, b, c = min(max(a/max(x1sql, 1e-30),-1),1), min(max(b/max(y1sql, 1e-30),-1),1), min(max(c/max(z1sql, 1e-30),-1),1)
  return square(a*x1.x+b*y1.x+c*z1.x-tmpv1.x) + square(a*x1.y+b*y1.y+c*z1.y-tmpv1.y) + square(a*x1.z+b*y1.z+c*z1.z-tmpv1.z)
end
  a, b, c = min(max(a/max(x1sql, 1e-30),-1),1), min(max(b/max(y1sql, 1e-30),-1),1), min(max(c/max(z1sql, 1e-30),-1),1)
  return square(a*x1.x+b*y1.x+c*z1.x-tmpv1.x) + square(a*x1.y+b*y1.y+c*z1.y-tmpv1.y) + square(a*x1.z+b*y1.z+c*z1.z-tmpv1.z)
end
@/lua/ge/extensions/gameplay/missions/startTrigger.lua
            candidate._qtId = id
            if cur.pos:squaredDistance(candidate.pos) < square(cur.radius+(mergeRadius or candidate.radius)) then
              table.insert(cluster, candidate)
@/lua/ge/extensions/gameplay/markers/missionMarker.lua
        candidate._qtId = id
        if pmi.pos:squaredDistance(candidate.markerInfo.missionMarker.pos) < square(1.5 + 1.5) then -- Fixed radius of 1.5m
          table.insert(cluster, candidate)
@/lua/ge/extensions/editor/slotTrafficEditor.lua
  for otherNid, data in pairs(mapNodes) do
    if data.pos:squaredDistance(node.pos) > square(maxConnectionRenderDistance) then
      -- remove the links
  local camNodeSqDist = camPos:squaredDistance(n.pos)
  if camNodeSqDist < square(clamp(editor.getPreference("gizmos.visualization.visualizationDrawDistance") * 0.5, 50, 250)) then
    debugDrawer:drawText(n.pos, String(tostring(nid)), linkBaseColor)
@/lua/vehicle/wheels.lua
      local energyBrakeSurfaceToAir = (wd.brakeSurfaceTemperature - tEnv) * wd.brakeCoolingArea * surfaceCooling
      local tempSquared = square(wd.brakeSurfaceTemperature + celsiusToKelvin)
      local energyRadiationToAir = square(tempSquared) * wd.kRadiationToAir * wd.brakeCoolingArea
      local tempSquared = square(wd.brakeSurfaceTemperature + celsiusToKelvin)
      local energyRadiationToAir = square(tempSquared) * wd.kRadiationToAir * wd.brakeCoolingArea
      local energyBrakeSurfaceToCore = (wd.brakeSurfaceTemperature - wd.brakeCoreTemperature) * wd.kSurfaceToCore * wd.brakeCoolingArea
      local distance = (startPosition - endPosition):length()
      local avgDeceleration = -(square(airspeed) - square(targetSpeed)) / (2 * distance)
      guihooks.message({txt = string.format("Brakingdistance from %dkm/h: %.2fm, G: %.2f", targetSpeed * 3.6, distance, avgDeceleration / -powertrain.currentGravity), context = {}}, 5, "vehicle.brakingdistance")
      local distance = (startPosition - endPosition):length()
      local avgDeceleration = -(square(airspeed) - square(targetSpeed)) / (2 * distance)
      guihooks.message({txt = string.format("Brakingdistance from %dkm/h: %.2fm, G: %.2f", targetSpeed * 3.6, distance, avgDeceleration / -powertrain.currentGravity), context = {}}, 5, "vehicle.brakingdistance")
@/lua/ge/extensions/gameplay/parking.lua
  if not parkingSpot.customFields.tags.perfect then -- randomize position and rotation slightly
    local offsetVal = 1 - square(vars.neatness)
    local xGap, yGap = max(0, parkingSpot.scl.x - width), max(0, parkingSpot.scl.y - length)
    local ps = psData.ps
    if psData.squaredDistance >= square(minDist) and psData.squaredDistance <= square(maxDist) and checkParkingSpot(vehId, ps) then
      if parkedVehData[vehId].parkingSpotId then
    local ps = psData.ps
    if psData.squaredDistance >= square(minDist) and psData.squaredDistance <= square(maxDist) and checkParkingSpot(vehId, ps) then
      if parkedVehData[vehId].parkingSpotId then
    for i, ps in ipairs(psList) do
      local minValue = min(fallbackValue, lerp(ratio, 1, square(i / psCount))) -- minValue is lower for nearer parking spots
      if not selected[ps.ps.name] and random() >= minValue then
  local maxDist = M.debugLevel >= 3 and 400 or vehData.maxDist
  if vehData.focusPos:squaredDistance(vehData.aheadPos) >= square(maxDist * 0.5) then -- focus pos and nearby parking spots low frequency update
    vehData.psList = findParkingSpots(vehData.aheadPos, 0, maxDist)

  local addedDist = square(math.abs(focus.dist or 0) * 0.15)
  local actualViewDist = clamp(viewDist + addedDist, 100, 300) -- view distance, adjusted by speed
    local ps = psData.ps
    if ps.pos:squaredDistance(focus.pos) > square(actualViewDist) and checkParkingSpot(newId, ps) then -- prevents respawn if player is too near to parking spot
      vehPool:setVeh(newId, true)
            local radius = otherVeh:isPlayerControlled() and 100 or 20
            if otherVeh:getPosition():squaredDistance(getObjectByID(vehId):getPosition()) < square(radius) then
              forceTeleport(vehId, nil, 100)
  -- only search for parking spots whenever needed (whenever look ahead point is far enough from the last position)
  if vars.baseProbability > 0 and respawnDelay == 0 and aheadPos:squaredDistance(lastPos) >= square(checkRadius) then -- updates parking spots if away from focus position
    local actualLookDist = lookDist
      height = focus.pos.z - height
      height = clamp(square(height) / 15, 0, 200)
      actualLookDist = actualLookDist + height
      activeRadius = activeRadius + max(0, focus.dirVec:dot(tempVec)) * 150
      if square(activeRadius) < focus.pos:squaredDistance(vehPos) then
        local valid = true
            local mapData = map.objects[veh:getId()]
            if vehPos:squaredDistance(mapData.pos) < square(innerRadius) then -- prevents respawning if too close
              valid = false
@/lua/ge/extensions/editor/aiViz.lua
  for otherNid, data in pairs(mapNodes) do
    if data.pos:squaredDistance(node.pos) > square(maxConnectionRenderDistance) then
      -- remove the links
  local camNodeSqDist = camPos:squaredDistance(n.pos)
  if camNodeSqDist < square(clamp(editor.getPreference("gizmos.visualization.visualizationDrawDistance") * 0.5, 50, 250)) then
    debugDrawer:drawText(n.pos, String(tostring(nid)), linkBaseColor)
@/lua/ge/extensions/freeroam/facilities.lua
    if obj then
      maxDistSqr = math.max(maxDistSqr, (obj:getPosition()-center):squaredLength() + square(pair[3] or 6))
    end
@/gameplay/missions/automation_test_track/flowgraph/001-Dam/customNodes/hitTargetNode.lua
    local targetDistSq = self.pos:squaredDistance(self.targetPos)
    if targetDistSq <= square(self.targetRadius) and targetDistSq < bestDist then
      local dir = self.pos - self.centerPos